POI Opinion API Offline
Send what your users think about any POI that our APIs return (truck parkings, campsites, camper stops, fuel stations, cameras and more): a star rating with a text opinion, a reply to a published opinion, a helpful / not helpful vote on an opinion, an "overnight stay OK?" vote on the place, photos and short videos (of an opinion or of the place itself, with the position and view direction where the file has it). Opinions, replies, photos and videos are published only after moderation. Uploads are safe to resend: send client_upload_id and keep the file on the device while the answer says retryable (storage full or busy), then send it again after retry_after seconds; action upload_status tells whether uploads are accepted now. Compress on the device before uploading to save call units (see client_checks); larger photos and longer videos are still accepted but compressed or trimmed by the server at more call units. Published content comes back in the truck-route answer on each parking row: opinions (average stars, count, the newest opinions with replies, votes, photos and videos), overnight_votes, place photos and place videos. Wrong position? action propose_location sends a corrected position (lat, lng, optional entrance_lat / entrance_lng, note, photo_id) for a parking row: at most 2000 m from the published point (more: 422 move_too_far), one open proposal per end user and place (a resend replaces it), checked by a moderator before the published position changes. Identify the POI with ext_source and ext_id (ext_id = the id field of the row in our API answer). Send user_ref, your own stable id of the end user: limits and votes count per end user.
POST https://nakordoni.eu/api/v2/data/poi-opinion
— քվոտայի դաս: cheap
| Պարամետր | Նկարագրություն |
|---|---|
action | (JSON body or query) submit (default) | reply | vote | vote_overnight | add_photo | add_place_photo | add_video | add_place_video | upload_status | propose_location | mine. |
user_ref | (JSON body or query, required) Your stable id of the end user (1-128 characters; send a hash, not an e-mail). One end user = one vote per opinion / place; per end user per day at most 5 opinions, 20 replies, 200 votes (vote and vote_overnight together) and 20 photos. |
ext_source | (JSON body or query) POI kind as in our answers: parking (truck-route parkings incl. campsite and camper_stop rows), poi, fuel, camera, report, limit, incident. For submit, vote_overnight, add_place_photo, propose_location (parking only). |
ext_id | (JSON body or query) The id field of that POI row in our API answer. |
lat | (JSON body or query) POI latitude — required with lng, name (and country) the first time a POI gets an opinion, vote or place photo. For add_photo: the photo position when the image has no GPS. For propose_location: the proposed new latitude (with lng, required). |
lng | (JSON body or query) POI longitude (see lat). |
name | (JSON body or query) POI name (first use of a POI). |
country | (JSON body or query) POI country ISO code (first use of a POI). |
stars | (JSON body, submit) 1-5. |
text | (JSON body) submit: 10-2000 characters; reply: 2-1000 characters. Texts with offensive words are refused with 422 profanity_needs_edit and the flagged words (nothing is stored). |
lang | (JSON body) Language of the text: en, de, fr, it, pl, uk, ru, cs, sk, ro, hu, bg, mk, ka (default en). |
author_name | (JSON body, optional) Shown name, at most 100 characters (default "Driver"). |
recommend | (JSON body, submit, optional) true / false. |
opinion_id | (JSON body or query) reply / vote / add_photo: the opinion id (vote also takes a reply id). A reply to a reply joins the top opinion (one level). |
vote | (JSON body, vote) up | down | none. Changing the vote replaces it; the same vote again changes nothing. |
overnight_ok | (JSON body, vote_overnight) yes | no | none — is an overnight stay OK at this place. |
image_base64 | (JSON body) One photo, JPEG / PNG / WebP, up to 8 MB as sent; up to 25 MB accepted and re-encoded by the server (JPEG, longest side 2560 px, x2 call units, answer compressed_by_server, original_bytes, stored_bytes; pictures over 24 megapixels are downscaled the same way and the answer adds original_megapixels), at least 200 x 200 px (or the multipart field "image" with the other fields in the query). submit (optional), add_photo (own opinion), add_place_photo (photo of the place). At most 5 photos per end user per place (place and opinion photos together, rejected ones do not count), at most 4 photos per opinion and 20 per end user per day. GPS position, altitude, view direction and capture time are read from the photo EXIF; the published file carries no metadata. |
photo_lat | (JSON body or query) submit / add_place_photo: photo position when the image has no GPS, with photo_lng, photo_heading (0-359) and photo_captured_at (ISO 8601). add_photo uses lat, lng, heading, captured_at. |
photo_lng | (JSON body or query) See photo_lat. |
photo_heading | (JSON body or query) See photo_lat. |
photo_captured_at | (JSON body or query) See photo_lat. |
heading | (JSON body or query) add_photo / add_video: view direction 0-359 when the file has none (add_place_video accepts it too). |
captured_at | (JSON body or query) add_photo / add_video: capture time ISO 8601 when the file has none (add_place_video accepts it too). Always the time the photo / video was TAKEN, also when it is uploaded later. |
video | (multipart form field) add_video (own opinion) / add_place_video (video of the place): ONE video, MP4, MOV or WebM (the file content is checked, not the name), at most 95 MB; up to 60 seconds served as sent, up to 180 seconds accepted and trimmed by the server to the first 60 seconds (x2 call units, answer trimmed_by_server, original_seconds). The other fields go as form fields or in the query. At most 1 video per end user per place (place and opinion videos together, rejected ones do not count), 3 per end user per day. Position, view direction and capture time are read from the video metadata (else lat / lng / heading / captured_at; video_lat ... for add_place_video); the published video is converted to MP4 (H.264, at most 1280 px) and carries no metadata. Published only after moderation. |
video_base64 | (JSON body) A small video (at most 8 MB) instead of the multipart field "video". |
video_lat | (JSON body or query) add_place_video: video position when the video has none, with video_lng, video_heading (0-359), video_captured_at (ISO 8601). |
video_lng | (JSON body or query) See video_lat. |
video_heading | (JSON body or query) See video_lat. |
video_captured_at | (JSON body or query) See video_lat. |
client_upload_id | (JSON body or query, optional) add_photo / add_place_photo / add_video / add_place_video: your id of this upload (a UUID, at most 64 characters), kept per end user. Sending the same upload again with the same client_upload_id answers the first result again (same photo / video id, replayed true): nothing is stored twice and no limit counts twice. |
entrance_lat | (JSON body, propose_location, optional) Position of the entrance of the place, with entrance_lng (both or neither). Kept for the moderator; it is not published. |
entrance_lng | (JSON body, propose_location, optional) See entrance_lat. |
note | (JSON body, propose_location, optional) Why the position is wrong, at most 500 characters (shown to the moderator only). |
photo_id | (JSON body, propose_location, optional) Id of an approved photo of this same place that shows the right position (the photo id from the photos[] of the truck-route row). |
Պատասխանի դաշտերը — պատասխանի ծրարի data օբյեկտի ներսում։ []-ը ցույց է տալիս ցուցակ, ուստի data.items[].name-ը յուրաքանչյուր տարրի name դաշտն է։ Դաշտը լինում է null, բացակայում է կամ դատարկ ցուցակ է, երբ արժեք չունենք․ լցոնող արժեք երբեք չենք դնում։
| Դաշտ | Նկարագրություն |
|---|---|
data.success | true when the request was accepted. |
data.opinion_id | submit: id of the new opinion (status pending until moderation). reply: reply_id and the top opinion_id. |
data.status | pending — the opinion / reply / photo is published only after moderation. |
data.photos[] / photo | Photos accepted with the request: id, status pending, width, height, lat, lng, heading, captured_at, geo_source (exif | client | none), flags (far_from_poi, future_capture). |
data.user_vote | vote: up | down | null after the call; changed, up_votes, down_votes of that opinion. |
data.overnight_votes | vote_overnight: yes, no, last_vote_at of the place; overnight_ok = this end user's vote. |
data.video | add_video / add_place_video: id, status pending, processing queued (converted in the background), duration_s, width, height, lat, lng, heading, captured_at, geo_source (exif | client | none), flags (far_from_poi, future_capture). |
usage.units | Only on a call that the server had to compress or trim: the call units of this call (x2 photo compression, x2 video trim), with units_extra and units_reason (photo_server_compress | video_server_trim); also in the X-Devapi-Units header. |
data.replayed | true when the answer is the stored result of an earlier upload with the same client_upload_id. |
data.accepting_uploads | upload_status (user_ref + ext_source + ext_id, no file): accepting_uploads true | false, reason (storage_full | moderation_backlog | storage_quota | null), retry_after (seconds or null), photo_slots_left_for_this_place, video_slots_left_for_this_place. Own limit 60 per minute per API key; not counted against opinions or votes. |
data.items[] | mine: the end user's own opinions and replies with their moderation status (pending | approved | rejected). |
data.proposal_id | propose_location: id of the proposal, status pending until a moderator rules on it; replaced true when it replaced the open proposal of the same end user for the same place (same proposal_id). Approved: the position in the truck-route parkings[] rows (lat, lon) changes; opinions, photos, videos and votes of the place stay attached. |
error.code | bad_request, user_ref_required, bad_ext_source, bad_ext_id, poi_details_required, bad_stars, bad_text, bad_vote, bad_overnight_ok, bad_photo_geo, bad_video_geo, image_required, video_required, upload_failed, bad_client_upload_id, bad_location, bad_entrance, bad_note, 404 opinion_not_found / poi_not_found, 409 not_approved / opinion_rejected / client_upload_id_used, 413 payload_too_large, 422 move_too_far (the proposed position is over 2000 m from the published one) / location_unchanged / bad_photo_ref / profanity_needs_edit (error.flagged) / not_an_image / not_a_video / unsupported_video_format / video_too_long (over 180 s) (422 = fix the request, error.retryable false), 403 key_blocked (error.action, error.reason: this action is blocked for the API key), 429 rate_limited (per end user per day: 5 opinions, 20 replies, 200 votes; or per API key: opinions 30/min 1000/day, replies 30/min 1000/day, votes 120/min 10000/day, propose_location 30/min 1000/day, 20/day per end user; Retry-After header) / photo_limit_place / photo_limit_opinion / video_limit_place (error.retryable false) / moderation_backlog (too many photos, or 1000 opinions and replies, of this key wait for moderation; Retry-After) / storage_quota (media storage of this key used up), 507 storage_full. storage_full (retry_after 3600), moderation_backlog (3600) and storage_quota (86400) carry error.retry_after (seconds), error.retryable true and a Retry-After header: keep the file on the device and send it again later with the same client_upload_id. |
Սեղմեք սարքում՝ զանգի միավորներ և ժամանակ խնայելու համար
Home Assistant-ի և հեռախոսների ինտեգրացիաների համար. բեռնելուց առաջ ֆայլը պատրաստեք սարքում: Չափազանց մեծ ֆայլերը չեն մերժվում. մենք ընդունում ենք դրանք և սերվերում սեղմում կամ կտրում ենք, բայց այդ զանգն այդ դեպքում ավելի շատ զանգի միավոր է արժենում:
- Լուսանկարներ. բեռնելուց առաջ փոքրացրեք առավելագույնը 8 ՄԲ (8388608 բայթ) չափի. 2560 px երկար կողմը լիովին բավարար է: Տեսակը՝ JPEG, PNG կամ WebP:
- Տեսանյութեր. կտրեք առավելագույնը 60 վայրկյանի և սեղմեք առավելագույնը 95 ՄԲ (99614720 բայթ) չափի: Տեսակը՝ MP4, MOV կամ WebM:
- Ավելի մեծ ֆայլերը դարձյալ ընդունվում են. մինչև 25 ՄԲ (26214400 բայթ) լուսանկարները մենք վերակոդավորում ենք (JPEG, երկար կողմը 2560 px, առավելագույնը 8 ՄԲ. լուսանկարի դիրքը պահպանվում է), մինչև 180 վայրկյան տեսանյութերը մենք կտրում ենք առաջին 60 վայրկյանի չափով: Այդպիսի զանգն արժե x2 զանգի միավոր (լուսանկար) կամ x2 (տեսանյութ). պատասխանում այդ դեպքում լինում է compressed_by_server / trimmed_by_server true, իսկ usage.units-ը ցույց է տալիս զանգի միավորները:
- Խիստ սահմաններ (մերժվում է, մի ուղարկեք). 25 ՄԲ-ից մեծ լուսանկարներ (413), 95 ՄԲ-ից մեծ (413, հարցման մարմնի սահմանը) կամ 180 վայրկյանից երկար տեսանյութեր (422):
- Յուրաքանչյուր վերջնական օգտատիրոջ համար յուրաքանչյուր վայրում առավելագույնը 5 լուսանկար և 1 տեսանյութ, իսկ յուրաքանչյուր կարծիքին՝ առավելագույնը 4 լուսանկար:
- Նախ կանչեք upload_status գործողությունը (user_ref, ext_source, ext_id. առանց ֆայլի): Այն վերադարձնում է accepting_uploads, retry_after, photo_slots_left_for_this_place և video_slots_left_for_this_place: Սա պարզելու համար մի փորձեք բեռնումներ:
- Երբ error.retryable true է (507 storage_full, 429 moderation_backlog կամ storage_quota, Retry-After վերնագրով). պահեք ֆայլը սարքում և retry_after վայրկյան հետո նորից ուղարկեք ՆՈՒՅՆ client_upload_id-ով: Երբ error.retryable false է. այդ ֆայլն այլևս երբեք մի ուղարկեք:
Օրինակ. փոքրացում սարքում (Pillow), հետո upload_status, հետո բեռնում. կրկնության թույլ տվող պատասխանի դեպքում պահեք ֆայլը և կրկին փորձեք:
# Home Assistant / phone integration (Python). The limits are the values in this section.
import io, uuid, requests
from PIL import Image, ImageOps
API = "https://nakordoni.eu/api/v2/data/poi-opinion"
HDR = {"Authorization": "Bearer NKD-DEV-XXXX-XXXX-XXXX"}
PHOTO_MAX_BYTES, PHOTO_SIDE = 8388608, 2560
def shrink_photo(path):
"""Resize on the device: JPEG, longest side <= PHOTO_SIDE, <= PHOTO_MAX_BYTES. Keeps EXIF (GPS position)."""
img = Image.open(path)
exif = img.info.get("exif", b"")
img = ImageOps.exif_transpose(img).convert("RGB")
img.thumbnail((PHOTO_SIDE, PHOTO_SIDE))
for quality in (90, 85, 80, 70, 60):
buf = io.BytesIO()
img.save(buf, "JPEG", quality=quality, exif=exif)
if buf.tell() <= PHOTO_MAX_BYTES:
return buf.getvalue()
return buf.getvalue() # still accepted; the server compresses it at x2 call units
def send_place_photo(item, queue):
# item: path, user_ref, ext_source, ext_id; client_upload_id is made ONCE and kept with the file
item.setdefault("client_upload_id", str(uuid.uuid4()))
who = {"user_ref": item["user_ref"], "ext_source": item["ext_source"], "ext_id": item["ext_id"]}
st = requests.post(API, headers=HDR, json={"action": "upload_status", **who}, timeout=30).json()["data"]
if not st["accepting_uploads"]:
queue.retry_later(item, st["retry_after"] or 3600) # keep the file
return "queued"
if st["photo_slots_left_for_this_place"] < 1:
return "limit reached for this place"
jpeg = shrink_photo(item["path"])
r = requests.post(API, headers=HDR, files={"image": ("photo.jpg", jpeg, "image/jpeg")}, timeout=120,
params={"action": "add_place_photo", "client_upload_id": item["client_upload_id"], **who})
body = r.json()
if body.get("ok"):
queue.done(item) # now the file may leave the queue
return "sent (%s units)" % body.get("usage", {}).get("units", 1)
err = body.get("error") or {}
if err.get("retryable"): # 507 storage_full, 429 moderation_backlog / storage_quota
queue.retry_later(item, int(r.headers.get("Retry-After") or err.get("retry_after") or 3600))
return "queued"
queue.drop(item) # retryable false: never send it again
return err.get("code")
# Videos: trim / compress on the device first (for example ffmpeg -t 60 -vf scale=-2:720 -crf 28),
# then the same flow with action add_place_video and files={"video": open(path, "rb")} (other fields as form data).Home Assistant ինտեգրացիա
Այս արտադրանքով Home Assistant ինտեգրացիան կարող է ուղարկել իր օգտատերերի կարծիքները մեր API-ների վերադարձրած վայրերի մասին, ավելացնել լուսանկարներ և տեսանյութեր և կրկին ցուցադրել հրապարակված բովանդակությունը: Ամեն ինչ, ինչ ուղարկվում է (կարծիքներ, պատասխաններ, լուսանկարներ, տեսանյութեր), չափավորվում է և երևում է միայն հաստատումից հետո:
Ինչ կարող է անել ինտեգրացիան
- Ուղարկել կարծիք POI-ի մասին. աստղեր (1-5) և տեքստ (submit գործողություն):
- Ավելացնել լուսանկարներ և տեսանյութեր կարծիքին (add_photo, add_video) կամ հենց վայրին (add_place_photo, add_place_video). յուրաքանչյուր կարծիքին առավելագույնը 4 լուսանկար:
- Քվեարկել կարծիքների օգտին կամ դեմ՝ օգտակար է թե ոչ (vote գործողություն. up | down | none), և քվեարկել՝ արդյոք վայրում գիշերելը ընդունելի է (vote_overnight գործողություն. yes | no | none):
- Պատասխանել կարծիքներին (reply գործողություն):
- Ամեն ինչ հետ կարդալ գոյություն ունեցող բեռնատարների երթուղիների API-ով, parkings[]-ի յուրաքանչյուր տողում. opinions {avg_stars, count, latest[]՝ id, replies, photos, videos, votes-ով}, overnight_votes, photos / photo_count, videos / video_count և camper_summary ավտոտնների երթուղիներում: Վերադարձվում է միայն հաստատված բովանդակություն:
POI թիրախը
- ext_source + ext_id-ը նույնականացնում են POI-ն. ext_id-ը բեռնատարների երթուղու պատասխանի տողի id դաշտն է (կայանատեղիի տողի համար ext_source-ը parking է):
- POI-ի առաջին զանգն ուղարկում է նաև lat, lng և name (և country, եթե ունեք): Նույն POI-ի հետագա զանգերին պետք են միայն ext_source + ext_id:
user_ref. մեկ id յուրաքանչյուր Home Assistant օգտատիրոջ համար
- Յուրաքանչյուր Home Assistant օգտատիրոջ համար ուղարկեք ՄԵԿ կայուն user_ref (օրինակ՝ Home Assistant օգտատիրոջ id-ի հեշը. երբեք էլ. փոստ կամ անուն): Մենք այն նորից հեշավորում ենք մեր կողմից և պահում ենք միայն այդ հեշը:
- Օգտատիրոջ սահմանաչափերը հաշվվում են ըստ user_ref-ի. օրինակ՝ յուրաքանչյուր վայրում 5 լուսանկար և 1 տեսանյութ, օրական 20 լուսանկար և 3 տեսանյութ, մեկ ձայն յուրաքանչյուր կարծիքի և յուրաքանչյուր վայրի համար: Յուրաքանչյուր զանգի համար նոր user_ref-ը ավելի շատ բեռնումներ չի տալիս. բանալու սահմանաչափերը շարունակում են գործել:
Առաջարկվող կառուցանյութեր (օրինակելի դիզայն ինտեգրատորների համար, ոչ թե մեր մատակարարած պաշտոնական ինտեգրացիա)
- nakordoni.submit_poi_opinion ծառայություն. դաշտեր՝ ext_source, ext_id, stars, text, lang, recommend (ըստ ցանկության). lat, lng, name՝ POI-ի առաջին զանգի ժամանակ:
- nakordoni.add_poi_photo ծառայություն. դաշտեր՝ ext_source, ext_id, opinion_id (ըստ ցանկության. դատարկ = վայրի լուսանկար) և camera_entity (տեսախցիկի լուսանկար) ԿԱՄ file_path (մեդիա ֆայլ, օրինակ՝ /media-ի տակ):
- nakordoni.add_poi_video ծառայություն. դաշտեր՝ ext_source, ext_id, opinion_id (ըստ ցանկության), file_path: Զանգից առաջ կտրեք և սեղմեք տեսանյութը:
- nakordoni.vote_overnight ծառայություն. դաշտեր՝ ext_source, ext_id, overnight_ok (yes | no | none):
- Սենսոր. ընտրված մեկ POI-ի (ըստ իր id-ի) կարծիքները բեռնատարների երթուղու պատասխանից. state = avg_stars, attributes = count, latest, overnight_votes, photo_count, video_count:
- Յուրաքանչյուր զանգի user_ref-ը գալիս է ծառայությունը կանչող Home Assistant օգտատիրոջից (զանգի համատեքստ), երբեք ծառայության դաշտից:
Սահմանաչափեր և ծախսեր
- Մեկ վերջնական օգտատիրոջ (user_ref) համար. յուրաքանչյուր վայրում 5 լուսանկար և 1 տեսանյութ (մերժվածները չեն հաշվվում), յուրաքանչյուր կարծիքին 4 լուսանկար, օրական 20 լուսանկար և 3 տեսանյութ. կարծիքների, պատասխանների և ձայների սահմանաչափերը՝ ինչպես նկարագրված է user_ref-ի բաժնում:
- Մեկ API բանալու համար. կարծիքներ՝ րոպեում 30 և օրական 1000, պատասխաններ՝ րոպեում 30 և օրական 1000, ձայներ՝ րոպեում 120 և օրական 10000, օրական 2000 լուսանկար և 300 տեսանյութ, չափավորման սպասող առավելագույնը 500 լուսանկար և 1000 կարծիք ու պատասխան, 5 ԳԲ մեդիա պահոց (5368709120 բայթ):
- Զանգի միավորներ. մեկ զանգ = արտադրանքի սովորական միավորները: 8 ՄԲ-ից մեծ լուսանկարը, որը սերվերը պետք է սեղմի, արժե x2. 60 վայրկյանից երկար տեսանյութը, որը սերվերը պետք է կտրի, արժե x2: x1 վճարելու համար փոքրացրեք և կտրեք Home Assistant-ում:
- 429. սպասեք: rate_limited, moderation_backlog և storage_quota պարունակում են Retry-After վերնագիր (moderation_backlog և storage_quota-ի դեպքում նաև error.retryable true. պահեք ֆայլը և ավելի ուշ նույն client_upload_id-ով նորից ուղարկեք): photo_limit_place, photo_limit_opinion և video_limit_place վերջնական են տվյալ վայրի կամ կարծիքի համար (error.retryable false):
- 507 storage_full. մեր մեդիա պահոցը կարճ ժամանակով լի է: error.retryable true. պահեք ֆայլը և retry_after վայրկյան հետո նորից ուղարկեք:
- 403 key_blocked. այս գործողությունը արգելափակված է ձեր API բանալու համար (error.action, error.reason): Մի կրկնեք. կապվեք մեզ հետ:
Գաղտնիություն
- Դիրքը և դիտման ուղղությունը (և նկարահանման ժամանակը) կարդացվում են լուսանկարի կամ տեսանյութի ֆայլից. photo_lat / photo_lng / photo_heading (կամ lat / lng / heading) ուղարկեք միայն այն դեպքում, երբ ֆայլում դրանք չկան: Տեսախցիկի լուսանկարները սովորաբար դիրք չունեն:
- Սարքի մետատվյալները (EXIF և տեսանյութի մետատվյալներ) հեռացվում են հրապարակված ֆայլերից:
- Դեմքերը և պետհամարանիշերը ստուգվում են չափավորման կողմից՝ նախքան լուսանկարի կամ տեսանյութի հրապարակումը:
Օրինակ (հատուկ Home Assistant ինտեգրացիա, ասինխրոն aiohttp). տեսախցիկի լուսանկար, փոքրացում Pillow-ով, upload_status, բեռնում client_upload_id-ով. կրկնության թույլ տվող պատասխանի դեպքում ֆայլը սպասում է /config/.storage-ում և retry_after-ից հետո նորից ուղարկվում է:
# Home Assistant custom integration (async, aiohttp). An EXAMPLE design, not an official integration.
# The limits are the values in this section (shared photo caps of the poi-opinion product).
import hashlib, io, json, os, time, uuid
from datetime import timedelta
from pathlib import Path
import aiohttp
from PIL import Image, ImageOps
from homeassistant.components.camera import async_get_image
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.event import async_track_time_interval
API = "https://nakordoni.eu/api/v2/data/poi-opinion"
PHOTO_FREE_BYTES, PHOTO_SIDE = 8388608, 2560
def shrink_photo(raw):
"""Runs in the executor: JPEG, longest side <= PHOTO_SIDE, <= PHOTO_FREE_BYTES. Keeps EXIF (position, direction)."""
img = Image.open(io.BytesIO(raw))
exif = img.info.get("exif", b"")
img = ImageOps.exif_transpose(img).convert("RGB")
img.thumbnail((PHOTO_SIDE, PHOTO_SIDE))
out = raw
for quality in (90, 85, 80, 70, 60):
buf = io.BytesIO()
img.save(buf, "JPEG", quality=quality, exif=exif)
out = buf.getvalue()
if len(out) <= PHOTO_FREE_BYTES:
break
return out # larger is still accepted: the server compresses it at x2 call units
class UploadQueue:
"""Files that wait for a retry, kept under /config/.storage/ so they survive a restart. Blocking: use the executor."""
def __init__(self, hass):
self.dir = hass.config.path(".storage", "nakordoni_poi_queue")
os.makedirs(self.dir, exist_ok=True)
def keep(self, item, jpeg, wait_s):
item["not_before"] = time.time() + wait_s
base = os.path.join(self.dir, item["client_upload_id"])
Path(base + ".jpg").write_bytes(jpeg)
Path(base + ".json").write_text(json.dumps(item))
def drop(self, item):
for ext in (".jpg", ".json"):
Path(self.dir, item["client_upload_id"] + ext).unlink(missing_ok=True)
def due(self):
out = []
for meta in Path(self.dir).glob("*.json"):
item = json.loads(meta.read_text())
if item["not_before"] <= time.time():
out.append((item, meta.with_suffix(".jpg").read_bytes()))
return out
async def send_photo(hass, api_key, queue, item, jpeg):
"""item: user_ref, ext_source, ext_id (+ lat, lng, name on the first call for a POI, opinion_id for add_photo)."""
item.setdefault("client_upload_id", str(uuid.uuid4())) # made ONCE per file, kept with the file
session = async_get_clientsession(hass)
hdr = {"Authorization": "Bearer " + api_key}
who = {k: str(item[k]) for k in ("user_ref", "ext_source", "ext_id")}
async with session.post(API, headers=hdr, json={"action": "upload_status", **who}) as r:
st = (await r.json(content_type=None))["data"]
if not st["accepting_uploads"]:
await hass.async_add_executor_job(queue.keep, item, jpeg, st["retry_after"] or 3600)
return "queued"
if st["photo_slots_left_for_this_place"] < 1:
await hass.async_add_executor_job(queue.drop, item)
return "limit reached for this place"
params = dict(who, client_upload_id=item["client_upload_id"],
action="add_photo" if item.get("opinion_id") else "add_place_photo")
for k in ("lat", "lng", "name", "opinion_id"):
if item.get(k) is not None:
params[k] = str(item[k])
form = aiohttp.FormData()
form.add_field("image", jpeg, filename="photo.jpg", content_type="image/jpeg")
async with session.post(API, headers=hdr, params=params, data=form,
timeout=aiohttp.ClientTimeout(total=120)) as r:
body = await r.json(content_type=None)
retry_header = r.headers.get("Retry-After")
if body.get("ok"):
await hass.async_add_executor_job(queue.drop, item)
return "sent, shown after moderation"
err = body.get("error") or {}
if err.get("retryable"): # 507 storage_full, 429 moderation_backlog / storage_quota
wait_s = int(retry_header or err.get("retry_after") or 3600)
await hass.async_add_executor_job(queue.keep, item, jpeg, wait_s)
return "queued for %d s" % wait_s
await hass.async_add_executor_job(queue.drop, item) # retryable false: never send this file again
return err.get("code")
async def async_setup_services(hass, api_key):
queue = await hass.async_add_executor_job(UploadQueue, hass)
async def add_poi_photo(call):
"""Service nakordoni.add_poi_photo: camera_entity (snapshot) OR file_path (media file)."""
if call.data.get("camera_entity"):
raw = (await async_get_image(hass, call.data["camera_entity"])).content
else:
raw = await hass.async_add_executor_job(Path(call.data["file_path"]).read_bytes)
jpeg = await hass.async_add_executor_job(shrink_photo, raw)
item = {k: call.data.get(k) for k in ("ext_source", "ext_id", "lat", "lng", "name", "opinion_id")}
# one stable id per Home Assistant user, never an e-mail; we hash it again on our side
item["user_ref"] = hashlib.sha256(("ha-" + (call.context.user_id or "system")).encode()).hexdigest()[:40]
await send_photo(hass, api_key, queue, item, jpeg)
async def retry_due(_now):
for item, jpeg in await hass.async_add_executor_job(queue.due):
await send_photo(hass, api_key, queue, item, jpeg)
hass.services.async_register("nakordoni", "add_poi_photo", add_poi_photo)
async_track_time_interval(hass, retry_due, timedelta(minutes=15))
# nakordoni.add_poi_video: trim / compress first (for example ffmpeg -t 60 -vf scale=-2:720 -crf 28, at most
# 95 MB), then the same flow with action add_video / add_place_video and the multipart field "video". curl -X POST "https://nakordoni.eu/api/v2/data/poi-opinion" \
-H "Authorization: Bearer NKD-DEV-XXXX-XXXX-XXXX" \
-H "Content-Type: application/json" \
-d '{
"action": "submit",
"user_ref": "u-7f3a9c",
"ext_source": "parking",
"ext_id": "348300711583683",
"lat": 63.81866,
"lng": -20.41976,
"name": "Truck parking",
"country": "IS",
"stars": 4,
"text": "Quiet place, flat gravel, room for a 7 m motorhome.",
"lang": "en",
"recommend": true
}'
Թարմացվել է