ApiV1Controller.php 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use Illuminate\Http\Request;
  4. use App\Http\Controllers\Controller;
  5. use Illuminate\Support\Str;
  6. use App\Util\ActivityPub\Helpers;
  7. use App\Util\Media\Filter;
  8. use Laravel\Passport\Passport;
  9. use Auth, Cache, DB, Storage, URL;
  10. use Illuminate\Support\Facades\Redis;
  11. use App\{
  12. Avatar,
  13. Bookmark,
  14. Collection,
  15. CollectionItem,
  16. DirectMessage,
  17. Follower,
  18. FollowRequest,
  19. Hashtag,
  20. HashtagFollow,
  21. Instance,
  22. Like,
  23. Media,
  24. Notification,
  25. Profile,
  26. Status,
  27. StatusHashtag,
  28. User,
  29. UserSetting,
  30. UserFilter,
  31. };
  32. use League\Fractal;
  33. use App\Transformer\Api\Mastodon\v1\{
  34. AccountTransformer,
  35. MediaTransformer,
  36. NotificationTransformer,
  37. StatusTransformer,
  38. };
  39. use App\Transformer\Api\{
  40. RelationshipTransformer,
  41. };
  42. use App\Http\Controllers\FollowerController;
  43. use League\Fractal\Serializer\ArraySerializer;
  44. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  45. use App\Http\Controllers\AccountController;
  46. use App\Http\Controllers\StatusController;
  47. use App\Jobs\AvatarPipeline\AvatarOptimize;
  48. use App\Jobs\CommentPipeline\CommentPipeline;
  49. use App\Jobs\LikePipeline\LikePipeline;
  50. use App\Jobs\MediaPipeline\MediaDeletePipeline;
  51. use App\Jobs\SharePipeline\SharePipeline;
  52. use App\Jobs\SharePipeline\UndoSharePipeline;
  53. use App\Jobs\StatusPipeline\NewStatusPipeline;
  54. use App\Jobs\StatusPipeline\StatusDelete;
  55. use App\Jobs\FollowPipeline\FollowPipeline;
  56. use App\Jobs\FollowPipeline\UnfollowPipeline;
  57. use App\Jobs\ImageOptimizePipeline\ImageOptimize;
  58. use App\Jobs\VideoPipeline\{
  59. VideoOptimize,
  60. VideoPostProcess,
  61. VideoThumbnail
  62. };
  63. use App\Services\{
  64. AccountService,
  65. BookmarkService,
  66. BouncerService,
  67. CollectionService,
  68. FollowerService,
  69. HashtagService,
  70. InstanceService,
  71. LikeService,
  72. NetworkTimelineService,
  73. NotificationService,
  74. MediaService,
  75. MediaPathService,
  76. ProfileStatusService,
  77. PublicTimelineService,
  78. ReblogService,
  79. RelationshipService,
  80. SearchApiV2Service,
  81. StatusService,
  82. MediaBlocklistService,
  83. SnowflakeService,
  84. UserFilterService
  85. };
  86. use App\Util\Lexer\Autolink;
  87. use App\Util\Lexer\PrettyNumber;
  88. use App\Util\Localization\Localization;
  89. use App\Util\Media\License;
  90. use App\Jobs\MediaPipeline\MediaSyncLicensePipeline;
  91. use App\Services\DiscoverService;
  92. use App\Services\CustomEmojiService;
  93. use App\Services\MarkerService;
  94. use App\Models\Conversation;
  95. use App\Jobs\FollowPipeline\FollowAcceptPipeline;
  96. use App\Jobs\FollowPipeline\FollowRejectPipeline;
  97. use Illuminate\Support\Facades\RateLimiter;
  98. use Purify;
  99. use Carbon\Carbon;
  100. use App\Http\Resources\MastoApi\FollowedTagResource;
  101. class ApiV1Controller extends Controller
  102. {
  103. protected $fractal;
  104. const PF_API_ENTITY_KEY = "_pe";
  105. public function __construct()
  106. {
  107. $this->fractal = new Fractal\Manager();
  108. $this->fractal->setSerializer(new ArraySerializer());
  109. }
  110. public function json($res, $code = 200, $headers = [])
  111. {
  112. return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
  113. }
  114. public function getApp(Request $request)
  115. {
  116. if(!$request->user()) {
  117. return response('', 403);
  118. }
  119. $client = $request->user()->token()->client;
  120. $res = [
  121. 'name' => $client->name,
  122. 'website' => null,
  123. 'vapid_key' => null
  124. ];
  125. return $this->json($res);
  126. }
  127. public function apps(Request $request)
  128. {
  129. abort_if(!config_cache('pixelfed.oauth_enabled'), 404);
  130. $this->validate($request, [
  131. 'client_name' => 'required',
  132. 'redirect_uris' => 'required'
  133. ]);
  134. $uris = implode(',', explode('\n', $request->redirect_uris));
  135. $client = Passport::client()->forceFill([
  136. 'user_id' => null,
  137. 'name' => e($request->client_name),
  138. 'secret' => Str::random(40),
  139. 'redirect' => $uris,
  140. 'personal_access_client' => false,
  141. 'password_client' => false,
  142. 'revoked' => false,
  143. ]);
  144. $client->save();
  145. $res = [
  146. 'id' => (string) $client->id,
  147. 'name' => $client->name,
  148. 'website' => null,
  149. 'redirect_uri' => $client->redirect,
  150. 'client_id' => (string) $client->id,
  151. 'client_secret' => $client->secret,
  152. 'vapid_key' => null
  153. ];
  154. return $this->json($res, 200, [
  155. 'Access-Control-Allow-Origin' => '*'
  156. ]);
  157. }
  158. /**
  159. * GET /api/v1/accounts/verify_credentials
  160. *
  161. *
  162. * @return \App\Transformer\Api\AccountTransformer
  163. */
  164. public function verifyCredentials(Request $request)
  165. {
  166. $user = $request->user();
  167. abort_if(!$user, 403);
  168. abort_if($user->status != null, 403);
  169. $res = $request->has(self::PF_API_ENTITY_KEY) ? AccountService::get($user->profile_id) : AccountService::getMastodon($user->profile_id);
  170. $res['source'] = [
  171. 'privacy' => $res['locked'] ? 'private' : 'public',
  172. 'sensitive' => false,
  173. 'language' => $user->language ?? 'en',
  174. 'note' => strip_tags($res['note']),
  175. 'fields' => []
  176. ];
  177. return $this->json($res);
  178. }
  179. /**
  180. * GET /api/v1/accounts/{id}
  181. *
  182. * @param integer $id
  183. *
  184. * @return \App\Transformer\Api\AccountTransformer
  185. */
  186. public function accountById(Request $request, $id)
  187. {
  188. $res = $request->has(self::PF_API_ENTITY_KEY) ? AccountService::get($id, true) : AccountService::getMastodon($id, true);
  189. if(!$res) {
  190. return response()->json(['error' => 'Record not found'], 404);
  191. }
  192. return $this->json($res);
  193. }
  194. /**
  195. * PATCH /api/v1/accounts/update_credentials
  196. *
  197. * @return \App\Transformer\Api\AccountTransformer
  198. */
  199. public function accountUpdateCredentials(Request $request)
  200. {
  201. abort_if(!$request->user(), 403);
  202. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  203. abort_if(BouncerService::checkIp($request->ip()), 404);
  204. }
  205. $this->validate($request, [
  206. 'avatar' => 'sometimes|mimetypes:image/jpeg,image/png|max:' . config('pixelfed.max_avatar_size'),
  207. 'display_name' => 'nullable|string|max:30',
  208. 'note' => 'nullable|string|max:200',
  209. 'locked' => 'nullable',
  210. 'website' => 'nullable|string|max:120',
  211. // 'source.privacy' => 'nullable|in:unlisted,public,private',
  212. // 'source.sensitive' => 'nullable|boolean'
  213. ], [
  214. 'required' => 'The :attribute field is required.',
  215. 'avatar.mimetypes' => 'The file must be in jpeg or png format',
  216. 'avatar.max' => 'The :attribute exceeds the file size limit of ' . PrettyNumber::size(config('pixelfed.max_avatar_size'), true, false),
  217. ]);
  218. $user = $request->user();
  219. $profile = $user->profile;
  220. $settings = $user->settings;
  221. $changes = false;
  222. $other = array_merge(AccountService::defaultSettings()['other'], $settings->other ?? []);
  223. $syncLicenses = false;
  224. $licenseChanged = false;
  225. $composeSettings = array_merge(AccountService::defaultSettings()['compose_settings'], $settings->compose_settings ?? []);
  226. if($request->has('avatar')) {
  227. $av = Avatar::whereProfileId($profile->id)->first();
  228. if($av) {
  229. $currentAvatar = storage_path('app/'.$av->media_path);
  230. $file = $request->file('avatar');
  231. $path = "public/avatars/{$profile->id}";
  232. $name = strtolower(str_random(6)). '.' . $file->guessExtension();
  233. $request->file('avatar')->storePubliclyAs($path, $name);
  234. $av->media_path = "{$path}/{$name}";
  235. $av->save();
  236. Cache::forget("avatar:{$profile->id}");
  237. Cache::forget('user:account:id:'.$user->id);
  238. AvatarOptimize::dispatch($user->profile, $currentAvatar);
  239. }
  240. $changes = true;
  241. }
  242. if($request->has('source[language]')) {
  243. $lang = $request->input('source[language]');
  244. if(in_array($lang, Localization::languages())) {
  245. $user->language = $lang;
  246. $changes = true;
  247. $other['language'] = $lang;
  248. }
  249. }
  250. if($request->has('website')) {
  251. $website = $request->input('website');
  252. if($website != $profile->website) {
  253. if($website) {
  254. if(!strpos($website, '.')) {
  255. $website = null;
  256. }
  257. if($website && !strpos($website, '://')) {
  258. $website = 'https://' . $website;
  259. }
  260. $host = parse_url($website, PHP_URL_HOST);
  261. $bannedInstances = InstanceService::getBannedDomains();
  262. if(in_array($host, $bannedInstances)) {
  263. $website = null;
  264. }
  265. }
  266. $profile->website = $website ? $website : null;
  267. $changes = true;
  268. }
  269. }
  270. if($request->has('display_name')) {
  271. $displayName = $request->input('display_name');
  272. if($displayName !== $user->name) {
  273. $user->name = $displayName;
  274. $profile->name = $displayName;
  275. $changes = true;
  276. }
  277. }
  278. if($request->has('note')) {
  279. $note = $request->input('note');
  280. if($note !== strip_tags($profile->bio)) {
  281. $profile->bio = Autolink::create()->autolink(strip_tags($note));
  282. $changes = true;
  283. }
  284. }
  285. if($request->has('locked')) {
  286. $locked = $request->input('locked') == 'true';
  287. if($profile->is_private != $locked) {
  288. $profile->is_private = $locked;
  289. $changes = true;
  290. }
  291. }
  292. if($request->has('reduce_motion')) {
  293. $reduced = $request->input('reduce_motion');
  294. if($settings->reduce_motion != $reduced) {
  295. $settings->reduce_motion = $reduced;
  296. $changes = true;
  297. }
  298. }
  299. if($request->has('high_contrast_mode')) {
  300. $contrast = $request->input('high_contrast_mode');
  301. if($settings->high_contrast_mode != $contrast) {
  302. $settings->high_contrast_mode = $contrast;
  303. $changes = true;
  304. }
  305. }
  306. if($request->has('video_autoplay')) {
  307. $autoplay = $request->input('video_autoplay');
  308. if($settings->video_autoplay != $autoplay) {
  309. $settings->video_autoplay = $autoplay;
  310. $changes = true;
  311. }
  312. }
  313. if($request->has('license')) {
  314. $license = $request->input('license');
  315. abort_if(!in_array($license, License::keys()), 422, 'Invalid media license id');
  316. $syncLicenses = $request->input('sync_licenses') == true;
  317. abort_if($syncLicenses && Cache::get('pf:settings:mls_recently:'.$user->id) == 2, 422, 'You can only sync licenses twice per 24 hours');
  318. if($composeSettings['default_license'] != $license) {
  319. $composeSettings['default_license'] = $license;
  320. $licenseChanged = true;
  321. $changes = true;
  322. }
  323. }
  324. if($request->has('media_descriptions')) {
  325. $md = $request->input('media_descriptions') == true;
  326. if($composeSettings['media_descriptions'] != $md) {
  327. $composeSettings['media_descriptions'] = $md;
  328. $changes = true;
  329. }
  330. }
  331. if($request->has('crawlable')) {
  332. $crawlable = $request->input('crawlable');
  333. if($settings->crawlable != $crawlable) {
  334. $settings->crawlable = $crawlable;
  335. $changes = true;
  336. }
  337. }
  338. if($request->has('show_profile_follower_count')) {
  339. $show_profile_follower_count = $request->input('show_profile_follower_count');
  340. if($settings->show_profile_follower_count != $show_profile_follower_count) {
  341. $settings->show_profile_follower_count = $show_profile_follower_count;
  342. $changes = true;
  343. }
  344. }
  345. if($request->has('show_profile_following_count')) {
  346. $show_profile_following_count = $request->input('show_profile_following_count');
  347. if($settings->show_profile_following_count != $show_profile_following_count) {
  348. $settings->show_profile_following_count = $show_profile_following_count;
  349. $changes = true;
  350. }
  351. }
  352. if($request->has('public_dm')) {
  353. $public_dm = $request->input('public_dm');
  354. if($settings->public_dm != $public_dm) {
  355. $settings->public_dm = $public_dm;
  356. $changes = true;
  357. }
  358. }
  359. if($request->has('source[privacy]')) {
  360. $scope = $request->input('source[privacy]');
  361. if(in_array($scope, ['public', 'private', 'unlisted'])) {
  362. if($composeSettings['default_scope'] != $scope) {
  363. $composeSettings['default_scope'] = $profile->is_private ? 'private' : $scope;
  364. $changes = true;
  365. }
  366. }
  367. }
  368. if($request->has('disable_embeds')) {
  369. $disabledEmbeds = $request->input('disable_embeds');
  370. if($other['disable_embeds'] != $disabledEmbeds) {
  371. $other['disable_embeds'] = $disabledEmbeds;
  372. $changes = true;
  373. }
  374. }
  375. if($changes) {
  376. $settings->other = $other;
  377. $settings->compose_settings = $composeSettings;
  378. $settings->save();
  379. $user->save();
  380. $profile->save();
  381. Cache::forget('profile:settings:' . $profile->id);
  382. Cache::forget('user:account:id:' . $profile->user_id);
  383. Cache::forget('profile:follower_count:' . $profile->id);
  384. Cache::forget('profile:following_count:' . $profile->id);
  385. Cache::forget('profile:embed:' . $profile->id);
  386. Cache::forget('profile:compose:settings:' . $user->id);
  387. Cache::forget('profile:view:'.$user->username);
  388. AccountService::del($user->profile_id);
  389. }
  390. if($syncLicenses && $licenseChanged) {
  391. $key = 'pf:settings:mls_recently:'.$user->id;
  392. $val = Cache::has($key) ? 2 : 1;
  393. Cache::put($key, $val, 86400);
  394. MediaSyncLicensePipeline::dispatch($user->id, $request->input('license'));
  395. }
  396. if($request->has(self::PF_API_ENTITY_KEY)) {
  397. $res = AccountService::get($user->profile_id, true);
  398. } else {
  399. $res = AccountService::getMastodon($user->profile_id, true);
  400. $res['bio'] = strip_tags($res['note']);
  401. $res = array_merge($res, $other);
  402. }
  403. return $this->json($res);
  404. }
  405. /**
  406. * GET /api/v1/accounts/{id}/followers
  407. *
  408. * @param integer $id
  409. *
  410. * @return \App\Transformer\Api\AccountTransformer
  411. */
  412. public function accountFollowersById(Request $request, $id)
  413. {
  414. abort_if(!$request->user(), 403);
  415. $account = AccountService::get($id);
  416. abort_if(!$account, 404);
  417. $pid = $request->user()->profile_id;
  418. $this->validate($request, [
  419. 'limit' => 'sometimes|integer|min:1|max:80'
  420. ]);
  421. $limit = $request->input('limit', 10);
  422. $napi = $request->has(self::PF_API_ENTITY_KEY);
  423. if(intval($pid) !== intval($account['id'])) {
  424. if($account['locked']) {
  425. if(!FollowerService::follows($pid, $account['id'])) {
  426. return [];
  427. }
  428. }
  429. if(AccountService::hiddenFollowers($id)) {
  430. return [];
  431. }
  432. if($request->has('page') && $request->user()->is_admin == false) {
  433. $page = (int) $request->input('page');
  434. if(($page * $limit) >= 100) {
  435. return [];
  436. }
  437. }
  438. }
  439. if($request->has('page')) {
  440. $res = DB::table('followers')
  441. ->select('id', 'profile_id', 'following_id')
  442. ->whereFollowingId($account['id'])
  443. ->orderByDesc('id')
  444. ->simplePaginate($limit)
  445. ->map(function($follower) use($napi) {
  446. return $napi ? AccountService::get($follower->profile_id, true) : AccountService::getMastodon($follower->profile_id, true);
  447. })
  448. ->filter(function($account) {
  449. return $account && isset($account['id']);
  450. })
  451. ->values()
  452. ->toArray();
  453. return $this->json($res);
  454. }
  455. $paginator = DB::table('followers')
  456. ->select('id', 'profile_id', 'following_id')
  457. ->whereFollowingId($account['id'])
  458. ->orderByDesc('id')
  459. ->cursorPaginate($limit)
  460. ->withQueryString();
  461. $link = null;
  462. if($paginator->onFirstPage()) {
  463. if($paginator->hasMorePages()) {
  464. $link = '<'.$paginator->nextPageUrl().'>; rel="prev"';
  465. }
  466. } else {
  467. if($paginator->previousPageUrl()) {
  468. $link = '<'.$paginator->previousPageUrl().'>; rel="next"';
  469. }
  470. if($paginator->hasMorePages()) {
  471. $link .= ($link ? ', ' : '') . '<'.$paginator->nextPageUrl().'>; rel="prev"';
  472. }
  473. }
  474. $res = $paginator->map(function($follower) use($napi) {
  475. return $napi ? AccountService::get($follower->profile_id, true) : AccountService::getMastodon($follower->profile_id, true);
  476. })
  477. ->filter(function($account) {
  478. return $account && isset($account['id']);
  479. })
  480. ->values()
  481. ->toArray();
  482. $headers = isset($link) ? ['Link' => $link] : [];
  483. return $this->json($res, 200, $headers);
  484. }
  485. /**
  486. * GET /api/v1/accounts/{id}/following
  487. *
  488. * @param integer $id
  489. *
  490. * @return \App\Transformer\Api\AccountTransformer
  491. */
  492. public function accountFollowingById(Request $request, $id)
  493. {
  494. abort_if(!$request->user(), 403);
  495. $account = AccountService::get($id);
  496. abort_if(!$account, 404);
  497. $pid = $request->user()->profile_id;
  498. $this->validate($request, [
  499. 'limit' => 'sometimes|integer|min:1|max:80'
  500. ]);
  501. $limit = $request->input('limit', 10);
  502. $napi = $request->has(self::PF_API_ENTITY_KEY);
  503. if(intval($pid) !== intval($account['id'])) {
  504. if($account['locked']) {
  505. if(!FollowerService::follows($pid, $account['id'])) {
  506. return [];
  507. }
  508. }
  509. if(AccountService::hiddenFollowing($id)) {
  510. return [];
  511. }
  512. if($request->has('page') && $request->user()->is_admin == false) {
  513. $page = (int) $request->input('page');
  514. if(($page * $limit) >= 100) {
  515. return [];
  516. }
  517. }
  518. }
  519. if($request->has('page')) {
  520. $res = DB::table('followers')
  521. ->select('id', 'profile_id', 'following_id')
  522. ->whereProfileId($account['id'])
  523. ->orderByDesc('id')
  524. ->simplePaginate($limit)
  525. ->map(function($follower) use($napi) {
  526. return $napi ? AccountService::get($follower->following_id, true) : AccountService::getMastodon($follower->following_id, true);
  527. })
  528. ->filter(function($account) {
  529. return $account && isset($account['id']);
  530. })
  531. ->values()
  532. ->toArray();
  533. return $this->json($res);
  534. }
  535. $paginator = DB::table('followers')
  536. ->select('id', 'profile_id', 'following_id')
  537. ->whereProfileId($account['id'])
  538. ->orderByDesc('id')
  539. ->cursorPaginate($limit)
  540. ->withQueryString();
  541. $link = null;
  542. if($paginator->onFirstPage()) {
  543. if($paginator->hasMorePages()) {
  544. $link = '<'.$paginator->nextPageUrl().'>; rel="prev"';
  545. }
  546. } else {
  547. if($paginator->previousPageUrl()) {
  548. $link = '<'.$paginator->previousPageUrl().'>; rel="next"';
  549. }
  550. if($paginator->hasMorePages()) {
  551. $link .= ($link ? ', ' : '') . '<'.$paginator->nextPageUrl().'>; rel="prev"';
  552. }
  553. }
  554. $res = $paginator->map(function($follower) use($napi) {
  555. return $napi ? AccountService::get($follower->following_id, true) : AccountService::getMastodon($follower->following_id, true);
  556. })
  557. ->filter(function($account) {
  558. return $account && isset($account['id']);
  559. })
  560. ->values()
  561. ->toArray();
  562. $headers = isset($link) ? ['Link' => $link] : [];
  563. return $this->json($res, 200, $headers);
  564. }
  565. /**
  566. * GET /api/v1/accounts/{id}/statuses
  567. *
  568. * @param integer $id
  569. *
  570. * @return \App\Transformer\Api\StatusTransformer
  571. */
  572. public function accountStatusesById(Request $request, $id)
  573. {
  574. $user = $request->user();
  575. $this->validate($request, [
  576. 'only_media' => 'nullable',
  577. 'media_type' => 'sometimes|string|in:photo,video',
  578. 'pinned' => 'nullable',
  579. 'exclude_replies' => 'nullable',
  580. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  581. 'since_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  582. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  583. 'limit' => 'nullable|integer|min:1|max:100'
  584. ]);
  585. $napi = $request->has(self::PF_API_ENTITY_KEY);
  586. $profile = $napi ? AccountService::get($id, true) : AccountService::getMastodon($id, true);
  587. if(!$profile || !isset($profile['id']) || !$user) {
  588. return $this->json(['error' => 'Account not found'], 404);
  589. }
  590. $limit = $request->limit ?? 20;
  591. $max_id = $request->max_id;
  592. $min_id = $request->min_id;
  593. if(!$max_id && !$min_id) {
  594. $min_id = 1;
  595. }
  596. $pid = $request->user()->profile_id;
  597. $scope = $request->only_media == true ?
  598. ['photo', 'photo:album', 'video', 'video:album'] :
  599. ['photo', 'photo:album', 'video', 'video:album', 'share', 'reply'];
  600. if($request->only_media && $request->has('media_type')) {
  601. $mt = $request->input('media_type');
  602. if($mt == 'video') {
  603. $scope = ['video', 'video:album'];
  604. }
  605. }
  606. if(intval($pid) === intval($profile['id'])) {
  607. $visibility = ['public', 'unlisted', 'private'];
  608. } else if($profile['locked']) {
  609. $following = FollowerService::follows($pid, $profile['id']);
  610. if(!$following) {
  611. return response('', 403);
  612. }
  613. $visibility = ['public', 'unlisted', 'private'];
  614. } else {
  615. $following = FollowerService::follows($pid, $profile['id']);
  616. $visibility = $following ? ['public', 'unlisted', 'private'] : ['public', 'unlisted'];
  617. }
  618. $dir = $min_id ? '>' : '<';
  619. $id = $min_id ?? $max_id;
  620. $res = Status::whereProfileId($profile['id'])
  621. ->whereNull('in_reply_to_id')
  622. ->whereNull('reblog_of_id')
  623. ->whereIn('type', $scope)
  624. ->where('id', $dir, $id)
  625. ->whereIn('scope', $visibility)
  626. ->limit($limit)
  627. ->orderByDesc('id')
  628. ->get()
  629. ->map(function($s) use($user, $napi, $profile) {
  630. try {
  631. $status = $napi ? StatusService::get($s->id, false) : StatusService::getMastodon($s->id, false);
  632. } catch (\Exception $e) {
  633. return false;
  634. }
  635. if($profile) {
  636. $status['account'] = $profile;
  637. }
  638. if($user && $status) {
  639. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $s->id);
  640. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $s->id);
  641. $status['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $s->id);
  642. }
  643. return $status;
  644. })
  645. ->filter(function($s) {
  646. return $s;
  647. })
  648. ->values();
  649. return $this->json($res);
  650. }
  651. /**
  652. * POST /api/v1/accounts/{id}/follow
  653. *
  654. * @param integer $id
  655. *
  656. * @return \App\Transformer\Api\RelationshipTransformer
  657. */
  658. public function accountFollowById(Request $request, $id)
  659. {
  660. abort_if(!$request->user(), 403);
  661. $user = $request->user();
  662. $target = Profile::where('id', '!=', $user->profile_id)
  663. ->whereNull('status')
  664. ->findOrFail($id);
  665. $private = (bool) $target->is_private;
  666. $remote = (bool) $target->domain;
  667. $blocked = UserFilter::whereUserId($target->id)
  668. ->whereFilterType('block')
  669. ->whereFilterableId($user->profile_id)
  670. ->whereFilterableType('App\Profile')
  671. ->exists();
  672. if($blocked == true) {
  673. abort(400, 'You cannot follow this user.');
  674. }
  675. $isFollowing = Follower::whereProfileId($user->profile_id)
  676. ->whereFollowingId($target->id)
  677. ->exists();
  678. // Following already, return empty relationship
  679. if($isFollowing == true) {
  680. $res = RelationshipService::get($user->profile_id, $target->id) ?? [];
  681. return $this->json($res);
  682. }
  683. // Rate limits, max 7500 followers per account
  684. if($user->profile->following_count && $user->profile->following_count >= Follower::MAX_FOLLOWING) {
  685. abort(400, 'You cannot follow more than ' . Follower::MAX_FOLLOWING . ' accounts');
  686. }
  687. if($private == true) {
  688. $follow = FollowRequest::firstOrCreate([
  689. 'follower_id' => $user->profile_id,
  690. 'following_id' => $target->id
  691. ]);
  692. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  693. (new FollowerController())->sendFollow($user->profile, $target);
  694. }
  695. } else {
  696. $follower = Follower::firstOrCreate([
  697. 'profile_id' => $user->profile_id,
  698. 'following_id' => $target->id
  699. ]);
  700. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  701. (new FollowerController())->sendFollow($user->profile, $target);
  702. }
  703. FollowPipeline::dispatch($follower)->onQueue('high');
  704. }
  705. RelationshipService::refresh($user->profile_id, $target->id);
  706. Cache::forget('profile:following:'.$target->id);
  707. Cache::forget('profile:followers:'.$target->id);
  708. Cache::forget('profile:following:'.$user->profile_id);
  709. Cache::forget('profile:followers:'.$user->profile_id);
  710. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  711. Cache::forget('user:account:id:'.$target->user_id);
  712. Cache::forget('user:account:id:'.$user->id);
  713. Cache::forget('profile:follower_count:'.$target->id);
  714. Cache::forget('profile:follower_count:'.$user->profile_id);
  715. Cache::forget('profile:following_count:'.$target->id);
  716. Cache::forget('profile:following_count:'.$user->profile_id);
  717. AccountService::del($user->profile_id);
  718. AccountService::del($target->id);
  719. $res = RelationshipService::get($user->profile_id, $target->id);
  720. return $this->json($res);
  721. }
  722. /**
  723. * POST /api/v1/accounts/{id}/unfollow
  724. *
  725. * @param integer $id
  726. *
  727. * @return \App\Transformer\Api\RelationshipTransformer
  728. */
  729. public function accountUnfollowById(Request $request, $id)
  730. {
  731. abort_if(!$request->user(), 403);
  732. $user = $request->user();
  733. $target = Profile::where('id', '!=', $user->profile_id)
  734. ->whereNull('status')
  735. ->findOrFail($id);
  736. $private = (bool) $target->is_private;
  737. $remote = (bool) $target->domain;
  738. $isFollowing = Follower::whereProfileId($user->profile_id)
  739. ->whereFollowingId($target->id)
  740. ->exists();
  741. if($isFollowing == false) {
  742. $followRequest = FollowRequest::whereFollowerId($user->profile_id)
  743. ->whereFollowingId($target->id)
  744. ->first();
  745. if($followRequest) {
  746. $followRequest->delete();
  747. RelationshipService::refresh($target->id, $user->profile_id);
  748. }
  749. $resource = new Fractal\Resource\Item($target, new RelationshipTransformer());
  750. $res = $this->fractal->createData($resource)->toArray();
  751. return $this->json($res);
  752. }
  753. Follower::whereProfileId($user->profile_id)
  754. ->whereFollowingId($target->id)
  755. ->delete();
  756. UnfollowPipeline::dispatch($user->profile_id, $target->id)->onQueue('high');
  757. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  758. (new FollowerController())->sendUndoFollow($user->profile, $target);
  759. }
  760. RelationshipService::refresh($user->profile_id, $target->id);
  761. Cache::forget('profile:following:'.$target->id);
  762. Cache::forget('profile:followers:'.$target->id);
  763. Cache::forget('profile:following:'.$user->profile_id);
  764. Cache::forget('profile:followers:'.$user->profile_id);
  765. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  766. Cache::forget('user:account:id:'.$target->user_id);
  767. Cache::forget('user:account:id:'.$user->id);
  768. Cache::forget('profile:follower_count:'.$target->id);
  769. Cache::forget('profile:follower_count:'.$user->profile_id);
  770. Cache::forget('profile:following_count:'.$target->id);
  771. Cache::forget('profile:following_count:'.$user->profile_id);
  772. AccountService::del($user->profile_id);
  773. AccountService::del($target->id);
  774. $res = RelationshipService::get($user->profile_id, $target->id);
  775. return $this->json($res);
  776. }
  777. /**
  778. * GET /api/v1/accounts/relationships
  779. *
  780. * @param array|integer $id
  781. *
  782. * @return \App\Services\RelationshipService
  783. */
  784. public function accountRelationshipsById(Request $request)
  785. {
  786. abort_if(!$request->user(), 403);
  787. $this->validate($request, [
  788. 'id' => 'required|array|min:1|max:20',
  789. 'id.*' => 'required|integer|min:1|max:' . PHP_INT_MAX
  790. ]);
  791. $napi = $request->has(self::PF_API_ENTITY_KEY);
  792. $pid = $request->user()->profile_id ?? $request->user()->profile->id;
  793. $res = collect($request->input('id'))
  794. ->filter(function($id) use($pid) {
  795. return intval($id) !== intval($pid);
  796. })
  797. ->map(function($id) use($pid, $napi) {
  798. return $napi ?
  799. RelationshipService::getWithDate($pid, $id) :
  800. RelationshipService::get($pid, $id);
  801. });
  802. return $this->json($res);
  803. }
  804. /**
  805. * GET /api/v1/accounts/search
  806. *
  807. *
  808. *
  809. * @return \App\Transformer\Api\AccountTransformer
  810. */
  811. public function accountSearch(Request $request)
  812. {
  813. abort_if(!$request->user(), 403);
  814. $this->validate($request, [
  815. 'q' => 'required|string|min:1|max:255',
  816. 'limit' => 'nullable|integer|min:1|max:40',
  817. 'resolve' => 'nullable'
  818. ]);
  819. $user = $request->user();
  820. $query = $request->input('q');
  821. $limit = $request->input('limit') ?? 20;
  822. $resolve = (bool) $request->input('resolve', false);
  823. $q = '%' . $query . '%';
  824. $profiles = Cache::remember('api:v1:accounts:search:' . sha1($query) . ':limit:' . $limit, 86400, function() use($q, $limit) {
  825. return Profile::whereNull('status')
  826. ->where('username', 'like', $q)
  827. ->orWhere('name', 'like', $q)
  828. ->limit($limit)
  829. ->pluck('id')
  830. ->map(function($id) {
  831. return AccountService::getMastodon($id);
  832. })
  833. ->filter(function($account) {
  834. return $account && isset($account['id']);
  835. });
  836. });
  837. return $this->json($profiles);
  838. }
  839. /**
  840. * GET /api/v1/blocks
  841. *
  842. *
  843. *
  844. * @return \App\Transformer\Api\AccountTransformer
  845. */
  846. public function accountBlocks(Request $request)
  847. {
  848. abort_if(!$request->user(), 403);
  849. $this->validate($request, [
  850. 'limit' => 'nullable|integer|min:1|max:40',
  851. 'page' => 'nullable|integer|min:1|max:10'
  852. ]);
  853. $user = $request->user();
  854. $limit = $request->input('limit') ?? 40;
  855. $blocked = UserFilter::select('filterable_id','filterable_type','filter_type','user_id')
  856. ->whereUserId($user->profile_id)
  857. ->whereFilterableType('App\Profile')
  858. ->whereFilterType('block')
  859. ->orderByDesc('id')
  860. ->simplePaginate($limit)
  861. ->pluck('filterable_id')
  862. ->map(function($id) {
  863. return AccountService::get($id, true);
  864. })
  865. ->filter(function($account) {
  866. return $account && isset($account['id']);
  867. })
  868. ->values();
  869. return $this->json($blocked);
  870. }
  871. /**
  872. * POST /api/v1/accounts/{id}/block
  873. *
  874. * @param integer $id
  875. *
  876. * @return \App\Transformer\Api\RelationshipTransformer
  877. */
  878. public function accountBlockById(Request $request, $id)
  879. {
  880. abort_if(!$request->user(), 403);
  881. $user = $request->user();
  882. $pid = $user->profile_id ?? $user->profile->id;
  883. if(intval($id) === intval($pid)) {
  884. abort(400, 'You cannot block yourself');
  885. }
  886. $profile = Profile::findOrFail($id);
  887. if($profile->user && $profile->user->is_admin == true) {
  888. abort(400, 'You cannot block an admin');
  889. }
  890. $count = UserFilterService::blockCount($pid);
  891. $maxLimit = intval(config('instance.user_filters.max_user_blocks'));
  892. if($count == 0) {
  893. $filterCount = UserFilter::whereUserId($pid)
  894. ->whereFilterType('block')
  895. ->get()
  896. ->map(function($rec) {
  897. return AccountService::get($rec->filterable_id, true);
  898. })
  899. ->filter(function($account) {
  900. return $account && isset($account['id']);
  901. })
  902. ->values()
  903. ->count();
  904. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_BLOCK_TEXT . $maxLimit . ' accounts');
  905. } else {
  906. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_BLOCK_TEXT . $maxLimit . ' accounts');
  907. }
  908. $followed = Follower::whereProfileId($profile->id)->whereFollowingId($pid)->first();
  909. if($followed) {
  910. $followed->delete();
  911. $profile->following_count = Follower::whereProfileId($profile->id)->count();
  912. $profile->save();
  913. $selfProfile = $user->profile;
  914. $selfProfile->followers_count = Follower::whereFollowingId($pid)->count();
  915. $selfProfile->save();
  916. FollowerService::remove($profile->id, $pid);
  917. AccountService::del($pid);
  918. AccountService::del($profile->id);
  919. }
  920. $following = Follower::whereProfileId($pid)->whereFollowingId($profile->id)->first();
  921. if($following) {
  922. $following->delete();
  923. $profile->followers_count = Follower::whereFollowingId($profile->id)->count();
  924. $profile->save();
  925. $selfProfile = $user->profile;
  926. $selfProfile->following_count = Follower::whereProfileId($pid)->count();
  927. $selfProfile->save();
  928. FollowerService::remove($pid, $profile->pid);
  929. AccountService::del($pid);
  930. AccountService::del($profile->id);
  931. }
  932. Notification::whereProfileId($pid)
  933. ->whereActorId($profile->id)
  934. ->get()
  935. ->map(function($n) use($pid) {
  936. NotificationService::del($pid, $n['id']);
  937. $n->forceDelete();
  938. });
  939. $filter = UserFilter::firstOrCreate([
  940. 'user_id' => $pid,
  941. 'filterable_id' => $profile->id,
  942. 'filterable_type' => 'App\Profile',
  943. 'filter_type' => 'block',
  944. ]);
  945. UserFilterService::block($pid, $id);
  946. RelationshipService::refresh($pid, $id);
  947. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  948. $res = $this->fractal->createData($resource)->toArray();
  949. return $this->json($res);
  950. }
  951. /**
  952. * POST /api/v1/accounts/{id}/unblock
  953. *
  954. * @param integer $id
  955. *
  956. * @return \App\Transformer\Api\RelationshipTransformer
  957. */
  958. public function accountUnblockById(Request $request, $id)
  959. {
  960. abort_if(!$request->user(), 403);
  961. $user = $request->user();
  962. $pid = $user->profile_id ?? $user->profile->id;
  963. if(intval($id) === intval($pid)) {
  964. abort(400, 'You cannot unblock yourself');
  965. }
  966. $profile = Profile::findOrFail($id);
  967. $filter = UserFilter::whereUserId($pid)
  968. ->whereFilterableId($profile->id)
  969. ->whereFilterableType('App\Profile')
  970. ->whereFilterType('block')
  971. ->first();
  972. if($filter) {
  973. $filter->delete();
  974. UserFilterService::unblock($pid, $profile->id);
  975. RelationshipService::refresh($pid, $id);
  976. }
  977. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  978. $res = $this->fractal->createData($resource)->toArray();
  979. return $this->json($res);
  980. }
  981. /**
  982. * GET /api/v1/custom_emojis
  983. *
  984. * Return custom emoji
  985. *
  986. * @return array
  987. */
  988. public function customEmojis()
  989. {
  990. return response(CustomEmojiService::all())->header('Content-Type', 'application/json');
  991. }
  992. /**
  993. * GET /api/v1/domain_blocks
  994. *
  995. * Return empty array
  996. *
  997. * @return array
  998. */
  999. public function accountDomainBlocks(Request $request)
  1000. {
  1001. abort_if(!$request->user(), 403);
  1002. return response()->json([]);
  1003. }
  1004. /**
  1005. * GET /api/v1/endorsements
  1006. *
  1007. * Return empty array
  1008. *
  1009. * @return array
  1010. */
  1011. public function accountEndorsements(Request $request)
  1012. {
  1013. abort_if(!$request->user(), 403);
  1014. return response()->json([]);
  1015. }
  1016. /**
  1017. * GET /api/v1/favourites
  1018. *
  1019. * Returns collection of liked statuses
  1020. *
  1021. * @return \App\Transformer\Api\StatusTransformer
  1022. */
  1023. public function accountFavourites(Request $request)
  1024. {
  1025. abort_if(!$request->user(), 403);
  1026. $this->validate($request, [
  1027. 'limit' => 'sometimes|integer|min:1|max:20'
  1028. ]);
  1029. $user = $request->user();
  1030. $maxId = $request->input('max_id');
  1031. $minId = $request->input('min_id');
  1032. $limit = $request->input('limit') ?? 10;
  1033. $res = Like::whereProfileId($user->profile_id)
  1034. ->when($maxId, function($q, $maxId) {
  1035. return $q->where('id', '<', $maxId);
  1036. })
  1037. ->when($minId, function($q, $minId) {
  1038. return $q->where('id', '>', $minId);
  1039. })
  1040. ->orderByDesc('id')
  1041. ->limit($limit)
  1042. ->get()
  1043. ->map(function($like) {
  1044. $status = StatusService::getMastodon($like['status_id'], false);
  1045. $status['favourited'] = true;
  1046. $status['like_id'] = $like->id;
  1047. $status['liked_at'] = str_replace('+00:00', 'Z', $like->created_at->format(DATE_RFC3339_EXTENDED));
  1048. return $status;
  1049. })
  1050. ->filter(function($status) {
  1051. return $status && isset($status['id'], $status['like_id']);
  1052. })
  1053. ->values();
  1054. if($res->count()) {
  1055. $ids = $res->map(function($status) {
  1056. return $status['like_id'];
  1057. });
  1058. $max = $ids->max();
  1059. $min = $ids->min();
  1060. $baseUrl = config('app.url') . '/api/v1/favourites?limit=' . $limit . '&';
  1061. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next",<'.$baseUrl.'min_id='.$min.'>; rel="prev"';
  1062. return $this->json($res, 200, ['Link' => $link]);
  1063. } else {
  1064. return $this->json($res);
  1065. }
  1066. }
  1067. /**
  1068. * POST /api/v1/statuses/{id}/favourite
  1069. *
  1070. * @param integer $id
  1071. *
  1072. * @return \App\Transformer\Api\StatusTransformer
  1073. */
  1074. public function statusFavouriteById(Request $request, $id)
  1075. {
  1076. abort_if(!$request->user(), 403);
  1077. $user = $request->user();
  1078. $status = StatusService::getMastodon($id, false);
  1079. abort_unless($status, 400);
  1080. $spid = $status['account']['id'];
  1081. if(intval($spid) !== intval($user->profile_id)) {
  1082. if($status['visibility'] == 'private') {
  1083. abort_if(!FollowerService::follows($user->profile_id, $spid), 403);
  1084. } else {
  1085. abort_if(!in_array($status['visibility'], ['public','unlisted']), 403);
  1086. }
  1087. }
  1088. abort_if(
  1089. Like::whereProfileId($user->profile_id)
  1090. ->where('created_at', '>', now()->subDay())
  1091. ->count() >= Like::MAX_PER_DAY,
  1092. 429
  1093. );
  1094. $blocks = UserFilterService::blocks($spid);
  1095. if($blocks && in_array($user->profile_id, $blocks)) {
  1096. abort(422);
  1097. }
  1098. $like = Like::firstOrCreate([
  1099. 'profile_id' => $user->profile_id,
  1100. 'status_id' => $status['id']
  1101. ]);
  1102. if($like->wasRecentlyCreated == true) {
  1103. $like->status_profile_id = $spid;
  1104. $like->is_comment = !empty($status['in_reply_to_id']);
  1105. $like->save();
  1106. Status::findOrFail($status['id'])->update([
  1107. 'likes_count' => ($status['favourites_count'] ?? 0) + 1
  1108. ]);
  1109. LikePipeline::dispatch($like)->onQueue('feed');
  1110. }
  1111. $status['favourited'] = true;
  1112. $status['favourites_count'] = $status['favourites_count'] + 1;
  1113. return $this->json($status);
  1114. }
  1115. /**
  1116. * POST /api/v1/statuses/{id}/unfavourite
  1117. *
  1118. * @param integer $id
  1119. *
  1120. * @return \App\Transformer\Api\StatusTransformer
  1121. */
  1122. public function statusUnfavouriteById(Request $request, $id)
  1123. {
  1124. abort_if(!$request->user(), 403);
  1125. $user = $request->user();
  1126. $status = Status::findOrFail($id);
  1127. if(intval($status->profile_id) !== intval($user->profile_id)) {
  1128. if($status->scope == 'private') {
  1129. abort_if(!$status->profile->followedBy($user->profile), 403);
  1130. } else {
  1131. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1132. }
  1133. }
  1134. $like = Like::whereProfileId($user->profile_id)
  1135. ->whereStatusId($status->id)
  1136. ->first();
  1137. if($like) {
  1138. $like->forceDelete();
  1139. $status->likes_count = $status->likes_count > 1 ? $status->likes_count - 1 : 0;
  1140. $status->save();
  1141. }
  1142. StatusService::del($status->id);
  1143. $res = StatusService::getMastodon($status->id, false);
  1144. $res['favourited'] = false;
  1145. return $this->json($res);
  1146. }
  1147. /**
  1148. * GET /api/v1/filters
  1149. *
  1150. * Return empty response since we filter server side
  1151. *
  1152. * @return array
  1153. */
  1154. public function accountFilters(Request $request)
  1155. {
  1156. abort_if(!$request->user(), 403);
  1157. return response()->json([]);
  1158. }
  1159. /**
  1160. * GET /api/v1/follow_requests
  1161. *
  1162. * Return array of Accounts that have sent follow requests
  1163. *
  1164. * @return \App\Transformer\Api\AccountTransformer
  1165. */
  1166. public function accountFollowRequests(Request $request)
  1167. {
  1168. abort_if(!$request->user(), 403);
  1169. $this->validate($request, [
  1170. 'limit' => 'sometimes|integer|min:1|max:100'
  1171. ]);
  1172. $user = $request->user();
  1173. $res = FollowRequest::whereFollowingId($user->profile->id)
  1174. ->limit($request->input('limit', 40))
  1175. ->pluck('follower_id')
  1176. ->map(function($id) {
  1177. return AccountService::getMastodon($id, true);
  1178. })
  1179. ->filter(function($acct) {
  1180. return $acct && isset($acct['id']);
  1181. })
  1182. ->values();
  1183. return $this->json($res);
  1184. }
  1185. /**
  1186. * POST /api/v1/follow_requests/{id}/authorize
  1187. *
  1188. * @param integer $id
  1189. *
  1190. * @return null
  1191. */
  1192. public function accountFollowRequestAccept(Request $request, $id)
  1193. {
  1194. abort_if(!$request->user(), 403);
  1195. $pid = $request->user()->profile_id;
  1196. $target = AccountService::getMastodon($id);
  1197. if(!$target) {
  1198. return response()->json(['error' => 'Record not found'], 404);
  1199. }
  1200. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1201. if(!$followRequest) {
  1202. return response()->json(['error' => 'Record not found'], 404);
  1203. }
  1204. $follower = $followRequest->follower;
  1205. $follow = new Follower();
  1206. $follow->profile_id = $follower->id;
  1207. $follow->following_id = $pid;
  1208. $follow->save();
  1209. $profile = Profile::findOrFail($pid);
  1210. $profile->followers_count++;
  1211. $profile->save();
  1212. AccountService::del($profile->id);
  1213. $profile = Profile::findOrFail($follower->id);
  1214. $profile->following_count++;
  1215. $profile->save();
  1216. AccountService::del($profile->id);
  1217. if($follower->domain != null && $follower->private_key === null) {
  1218. FollowAcceptPipeline::dispatch($followRequest)->onQueue('follow');
  1219. } else {
  1220. FollowPipeline::dispatch($follow);
  1221. $followRequest->delete();
  1222. }
  1223. RelationshipService::refresh($pid, $id);
  1224. $res = RelationshipService::get($pid, $id);
  1225. $res['followed_by'] = true;
  1226. return $this->json($res);
  1227. }
  1228. /**
  1229. * POST /api/v1/follow_requests/{id}/reject
  1230. *
  1231. * @param integer $id
  1232. *
  1233. * @return null
  1234. */
  1235. public function accountFollowRequestReject(Request $request, $id)
  1236. {
  1237. abort_if(!$request->user(), 403);
  1238. $pid = $request->user()->profile_id;
  1239. $target = AccountService::getMastodon($id);
  1240. if(!$target) {
  1241. return response()->json(['error' => 'Record not found'], 404);
  1242. }
  1243. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1244. if(!$followRequest) {
  1245. return response()->json(['error' => 'Record not found'], 404);
  1246. }
  1247. $follower = $followRequest->follower;
  1248. if($follower->domain != null && $follower->private_key === null) {
  1249. FollowRejectPipeline::dispatch($followRequest)->onQueue('follow');
  1250. } else {
  1251. $followRequest->delete();
  1252. }
  1253. RelationshipService::refresh($pid, $id);
  1254. $res = RelationshipService::get($pid, $id);
  1255. return $this->json($res);
  1256. }
  1257. /**
  1258. * GET /api/v1/suggestions
  1259. *
  1260. * Return empty array as we don't support suggestions
  1261. *
  1262. * @return null
  1263. */
  1264. public function accountSuggestions(Request $request)
  1265. {
  1266. abort_if(!$request->user(), 403);
  1267. // todo
  1268. return response()->json([]);
  1269. }
  1270. /**
  1271. * GET /api/v1/instance
  1272. *
  1273. * Information about the server.
  1274. *
  1275. * @return Instance
  1276. */
  1277. public function instance(Request $request)
  1278. {
  1279. $res = Cache::remember('api:v1:instance-data-response-v1', 1800, function () {
  1280. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  1281. if(config_cache('instance.admin.pid')) {
  1282. return AccountService::getMastodon(config_cache('instance.admin.pid'), true);
  1283. }
  1284. $admin = User::whereIsAdmin(true)->first();
  1285. return $admin && isset($admin->profile_id) ?
  1286. AccountService::getMastodon($admin->profile_id, true) :
  1287. null;
  1288. });
  1289. $stats = Cache::remember('api:v1:instance-data:stats', 43200, function () {
  1290. return [
  1291. 'user_count' => User::count(),
  1292. 'status_count' => Status::whereNull('uri')->count(),
  1293. 'domain_count' => Instance::count(),
  1294. ];
  1295. });
  1296. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1297. return config_cache('app.rules') ?
  1298. collect(json_decode(config_cache('app.rules'), true))
  1299. ->map(function($rule, $key) {
  1300. $id = $key + 1;
  1301. return [
  1302. 'id' => "{$id}",
  1303. 'text' => $rule
  1304. ];
  1305. })
  1306. ->toArray() : [];
  1307. });
  1308. return [
  1309. 'uri' => config('pixelfed.domain.app'),
  1310. 'title' => config('app.name'),
  1311. 'short_description' => config_cache('app.short_description'),
  1312. 'description' => config_cache('app.description'),
  1313. 'email' => config('instance.email'),
  1314. 'version' => '2.7.2 (compatible; Pixelfed ' . config('pixelfed.version') .')',
  1315. 'urls' => [
  1316. 'streaming_api' => 'wss://' . config('pixelfed.domain.app')
  1317. ],
  1318. 'stats' => $stats,
  1319. 'thumbnail' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
  1320. 'languages' => [config('app.locale')],
  1321. 'registrations' => (bool) config_cache('pixelfed.open_registration'),
  1322. 'approval_required' => false,
  1323. 'contact_account' => $contact,
  1324. 'rules' => $rules,
  1325. 'configuration' => [
  1326. 'media_attachments' => [
  1327. 'image_matrix_limit' => 16777216,
  1328. 'image_size_limit' => config('pixelfed.max_photo_size') * 1024,
  1329. 'supported_mime_types' => explode(',', config('pixelfed.media_types')),
  1330. 'video_frame_rate_limit' => 120,
  1331. 'video_matrix_limit' => 2304000,
  1332. 'video_size_limit' => config('pixelfed.max_photo_size') * 1024,
  1333. ],
  1334. 'polls' => [
  1335. 'max_characters_per_option' => 50,
  1336. 'max_expiration' => 2629746,
  1337. 'max_options' => 4,
  1338. 'min_expiration' => 300
  1339. ],
  1340. 'statuses' => [
  1341. 'characters_reserved_per_url' => 23,
  1342. 'max_characters' => (int) config('pixelfed.max_caption_length'),
  1343. 'max_media_attachments' => (int) config('pixelfed.max_album_length')
  1344. ]
  1345. ]
  1346. ];
  1347. });
  1348. return $this->json($res);
  1349. }
  1350. /**
  1351. * GET /api/v1/lists
  1352. *
  1353. * Return empty array as we don't support lists
  1354. *
  1355. * @return null
  1356. */
  1357. public function accountLists(Request $request)
  1358. {
  1359. abort_if(!$request->user(), 403);
  1360. return response()->json([]);
  1361. }
  1362. /**
  1363. * GET /api/v1/accounts/{id}/lists
  1364. *
  1365. * @param integer $id
  1366. *
  1367. * @return null
  1368. */
  1369. public function accountListsById(Request $request, $id)
  1370. {
  1371. abort_if(!$request->user(), 403);
  1372. return response()->json([]);
  1373. }
  1374. /**
  1375. * POST /api/v1/media
  1376. *
  1377. *
  1378. * @return MediaTransformer
  1379. */
  1380. public function mediaUpload(Request $request)
  1381. {
  1382. abort_if(!$request->user(), 403);
  1383. $this->validate($request, [
  1384. 'file.*' => [
  1385. 'required_without:file',
  1386. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1387. 'max:' . config_cache('pixelfed.max_photo_size'),
  1388. ],
  1389. 'file' => [
  1390. 'required_without:file.*',
  1391. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1392. 'max:' . config_cache('pixelfed.max_photo_size'),
  1393. ],
  1394. 'filter_name' => 'nullable|string|max:24',
  1395. 'filter_class' => 'nullable|alpha_dash|max:24',
  1396. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1397. ]);
  1398. $user = $request->user();
  1399. if($user->last_active_at == null) {
  1400. return [];
  1401. }
  1402. if(empty($request->file('file'))) {
  1403. return response('', 422);
  1404. }
  1405. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1406. $limitTtl = now()->addMinutes(15);
  1407. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1408. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1409. return $dailyLimit >= 1250;
  1410. });
  1411. abort_if($limitReached == true, 429);
  1412. $profile = $user->profile;
  1413. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1414. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1415. return Media::whereUserId($user->id)->sum('size') / 1000;
  1416. });
  1417. $limit = (int) config_cache('pixelfed.max_account_size');
  1418. if ($size >= $limit) {
  1419. abort(403, 'Account size limit reached.');
  1420. }
  1421. }
  1422. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1423. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1424. $photo = $request->file('file');
  1425. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1426. if(in_array($photo->getMimeType(), $mimes) == false) {
  1427. abort(403, 'Invalid or unsupported mime type.');
  1428. }
  1429. $storagePath = MediaPathService::get($user, 2);
  1430. $path = $photo->storePublicly($storagePath);
  1431. $hash = \hash_file('sha256', $photo);
  1432. $license = null;
  1433. $mime = $photo->getMimeType();
  1434. // if($photo->getMimeType() == 'image/heic') {
  1435. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1436. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1437. // $oldPath = $path;
  1438. // $path = str_replace('.heic', '.jpg', $path);
  1439. // $mime = 'image/jpeg';
  1440. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1441. // @unlink(storage_path("app/{$oldPath}"));
  1442. // }
  1443. $settings = UserSetting::whereUserId($user->id)->first();
  1444. if($settings && !empty($settings->compose_settings)) {
  1445. $compose = $settings->compose_settings;
  1446. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1447. $license = $compose['default_license'];
  1448. }
  1449. }
  1450. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1451. $media = new Media();
  1452. $media->status_id = null;
  1453. $media->profile_id = $profile->id;
  1454. $media->user_id = $user->id;
  1455. $media->media_path = $path;
  1456. $media->original_sha256 = $hash;
  1457. $media->size = $photo->getSize();
  1458. $media->mime = $mime;
  1459. $media->caption = $request->input('description');
  1460. $media->filter_class = $filterClass;
  1461. $media->filter_name = $filterName;
  1462. if($license) {
  1463. $media->license = $license;
  1464. }
  1465. $media->save();
  1466. switch ($media->mime) {
  1467. case 'image/jpeg':
  1468. case 'image/png':
  1469. ImageOptimize::dispatch($media)->onQueue('mmo');
  1470. break;
  1471. case 'video/mp4':
  1472. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1473. $preview_url = '/storage/no-preview.png';
  1474. $url = '/storage/no-preview.png';
  1475. break;
  1476. }
  1477. Cache::forget($limitKey);
  1478. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1479. $res = $this->fractal->createData($resource)->toArray();
  1480. $res['preview_url'] = $media->url(). '?v=' . time();
  1481. $res['url'] = $media->url(). '?v=' . time();
  1482. return $this->json($res);
  1483. }
  1484. /**
  1485. * PUT /api/v1/media/{id}
  1486. *
  1487. * @param integer $id
  1488. *
  1489. * @return MediaTransformer
  1490. */
  1491. public function mediaUpdate(Request $request, $id)
  1492. {
  1493. abort_if(!$request->user(), 403);
  1494. $this->validate($request, [
  1495. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1496. ]);
  1497. $user = $request->user();
  1498. $media = Media::whereUserId($user->id)
  1499. ->whereProfileId($user->profile_id)
  1500. ->findOrFail($id);
  1501. $executed = RateLimiter::attempt(
  1502. 'media:update:'.$user->id,
  1503. 10,
  1504. function() use($media, $request) {
  1505. $caption = Purify::clean($request->input('description'));
  1506. if($caption != $media->caption) {
  1507. $media->caption = $caption;
  1508. $media->save();
  1509. if($media->status_id) {
  1510. MediaService::del($media->status_id);
  1511. StatusService::del($media->status_id);
  1512. }
  1513. }
  1514. });
  1515. if(!$executed) {
  1516. return response()->json([
  1517. 'error' => 'Too many attempts. Try again in a few minutes.'
  1518. ], 429);
  1519. };
  1520. $fractal = new Fractal\Manager();
  1521. $fractal->setSerializer(new ArraySerializer());
  1522. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1523. return $this->json($fractal->createData($resource)->toArray());
  1524. }
  1525. /**
  1526. * GET /api/v1/media/{id}
  1527. *
  1528. * @param integer $id
  1529. *
  1530. * @return MediaTransformer
  1531. */
  1532. public function mediaGet(Request $request, $id)
  1533. {
  1534. abort_if(!$request->user(), 403);
  1535. $user = $request->user();
  1536. $media = Media::whereUserId($user->id)
  1537. ->whereNull('status_id')
  1538. ->findOrFail($id);
  1539. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1540. $res = $this->fractal->createData($resource)->toArray();
  1541. return $this->json($res);
  1542. }
  1543. /**
  1544. * POST /api/v2/media
  1545. *
  1546. *
  1547. * @return MediaTransformer
  1548. */
  1549. public function mediaUploadV2(Request $request)
  1550. {
  1551. abort_if(!$request->user(), 403);
  1552. $this->validate($request, [
  1553. 'file.*' => [
  1554. 'required_without:file',
  1555. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1556. 'max:' . config_cache('pixelfed.max_photo_size'),
  1557. ],
  1558. 'file' => [
  1559. 'required_without:file.*',
  1560. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1561. 'max:' . config_cache('pixelfed.max_photo_size'),
  1562. ],
  1563. 'filter_name' => 'nullable|string|max:24',
  1564. 'filter_class' => 'nullable|alpha_dash|max:24',
  1565. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length'),
  1566. 'replace_id' => 'sometimes'
  1567. ]);
  1568. $user = $request->user();
  1569. if($user->last_active_at == null) {
  1570. return [];
  1571. }
  1572. if(empty($request->file('file'))) {
  1573. return response('', 422);
  1574. }
  1575. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1576. $limitTtl = now()->addMinutes(15);
  1577. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1578. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1579. return $dailyLimit >= 1250;
  1580. });
  1581. abort_if($limitReached == true, 429);
  1582. $profile = $user->profile;
  1583. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1584. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1585. return Media::whereUserId($user->id)->sum('size') / 1000;
  1586. });
  1587. $limit = (int) config_cache('pixelfed.max_account_size');
  1588. if ($size >= $limit) {
  1589. abort(403, 'Account size limit reached.');
  1590. }
  1591. }
  1592. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1593. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1594. $photo = $request->file('file');
  1595. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1596. if(in_array($photo->getMimeType(), $mimes) == false) {
  1597. abort(403, 'Invalid or unsupported mime type.');
  1598. }
  1599. $storagePath = MediaPathService::get($user, 2);
  1600. $path = $photo->storePublicly($storagePath);
  1601. $hash = \hash_file('sha256', $photo);
  1602. $license = null;
  1603. $mime = $photo->getMimeType();
  1604. $settings = UserSetting::whereUserId($user->id)->first();
  1605. if($settings && !empty($settings->compose_settings)) {
  1606. $compose = $settings->compose_settings;
  1607. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1608. $license = $compose['default_license'];
  1609. }
  1610. }
  1611. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1612. if($request->has('replace_id')) {
  1613. $rpid = $request->input('replace_id');
  1614. $removeMedia = Media::whereNull('status_id')
  1615. ->whereUserId($user->id)
  1616. ->whereProfileId($profile->id)
  1617. ->where('created_at', '>', now()->subHours(2))
  1618. ->find($rpid);
  1619. if($removeMedia) {
  1620. $dateTime = Carbon::now();
  1621. MediaDeletePipeline::dispatch($removeMedia)
  1622. ->onQueue('mmo')
  1623. ->delay($dateTime->addMinutes(15));
  1624. }
  1625. }
  1626. $media = new Media();
  1627. $media->status_id = null;
  1628. $media->profile_id = $profile->id;
  1629. $media->user_id = $user->id;
  1630. $media->media_path = $path;
  1631. $media->original_sha256 = $hash;
  1632. $media->size = $photo->getSize();
  1633. $media->mime = $mime;
  1634. $media->caption = $request->input('description');
  1635. $media->filter_class = $filterClass;
  1636. $media->filter_name = $filterName;
  1637. if($license) {
  1638. $media->license = $license;
  1639. }
  1640. $media->save();
  1641. switch ($media->mime) {
  1642. case 'image/jpeg':
  1643. case 'image/png':
  1644. ImageOptimize::dispatch($media)->onQueue('mmo');
  1645. break;
  1646. case 'video/mp4':
  1647. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1648. $preview_url = '/storage/no-preview.png';
  1649. $url = '/storage/no-preview.png';
  1650. break;
  1651. }
  1652. Cache::forget($limitKey);
  1653. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1654. $res = $this->fractal->createData($resource)->toArray();
  1655. $res['preview_url'] = $media->url(). '?v=' . time();
  1656. $res['url'] = null;
  1657. return $this->json($res, 202);
  1658. }
  1659. /**
  1660. * GET /api/v1/mutes
  1661. *
  1662. *
  1663. * @return AccountTransformer
  1664. */
  1665. public function accountMutes(Request $request)
  1666. {
  1667. abort_if(!$request->user(), 403);
  1668. $this->validate($request, [
  1669. 'limit' => 'nullable|integer|min:1|max:40'
  1670. ]);
  1671. $user = $request->user();
  1672. $limit = $request->input('limit', 40);
  1673. $mutes = UserFilter::whereUserId($user->profile_id)
  1674. ->whereFilterableType('App\Profile')
  1675. ->whereFilterType('mute')
  1676. ->orderByDesc('id')
  1677. ->simplePaginate($limit)
  1678. ->pluck('filterable_id')
  1679. ->map(function($id) {
  1680. return AccountService::get($id, true);
  1681. })
  1682. ->filter(function($account) {
  1683. return $account && isset($account['id']);
  1684. })
  1685. ->values();
  1686. return $this->json($mutes);
  1687. }
  1688. /**
  1689. * POST /api/v1/accounts/{id}/mute
  1690. *
  1691. * @param integer $id
  1692. *
  1693. * @return RelationshipTransformer
  1694. */
  1695. public function accountMuteById(Request $request, $id)
  1696. {
  1697. abort_if(!$request->user(), 403);
  1698. $user = $request->user();
  1699. $pid = $user->profile_id;
  1700. if(intval($pid) === intval($id)) {
  1701. return $this->json(['error' => 'You cannot mute yourself'], 500);
  1702. }
  1703. $account = Profile::findOrFail($id);
  1704. $count = UserFilterService::muteCount($pid);
  1705. $maxLimit = intval(config('instance.user_filters.max_user_mutes'));
  1706. if($count == 0) {
  1707. $filterCount = UserFilter::whereUserId($pid)
  1708. ->whereFilterType('mute')
  1709. ->get()
  1710. ->map(function($rec) {
  1711. return AccountService::get($rec->filterable_id, true);
  1712. })
  1713. ->filter(function($account) {
  1714. return $account && isset($account['id']);
  1715. })
  1716. ->values()
  1717. ->count();
  1718. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT . $maxLimit . ' accounts');
  1719. } else {
  1720. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT . $maxLimit . ' accounts');
  1721. }
  1722. $filter = UserFilter::firstOrCreate([
  1723. 'user_id' => $pid,
  1724. 'filterable_id' => $account->id,
  1725. 'filterable_type' => 'App\Profile',
  1726. 'filter_type' => 'mute',
  1727. ]);
  1728. RelationshipService::refresh($pid, $id);
  1729. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1730. $res = $this->fractal->createData($resource)->toArray();
  1731. return $this->json($res);
  1732. }
  1733. /**
  1734. * POST /api/v1/accounts/{id}/unmute
  1735. *
  1736. * @param integer $id
  1737. *
  1738. * @return RelationshipTransformer
  1739. */
  1740. public function accountUnmuteById(Request $request, $id)
  1741. {
  1742. abort_if(!$request->user(), 403);
  1743. $user = $request->user();
  1744. $pid = $user->profile_id;
  1745. if(intval($pid) === intval($id)) {
  1746. return $this->json(['error' => 'You cannot unmute yourself'], 500);
  1747. }
  1748. $profile = Profile::findOrFail($id);
  1749. $filter = UserFilter::whereUserId($pid)
  1750. ->whereFilterableId($profile->id)
  1751. ->whereFilterableType('App\Profile')
  1752. ->whereFilterType('mute')
  1753. ->first();
  1754. if($filter) {
  1755. $filter->delete();
  1756. UserFilterService::unmute($pid, $profile->id);
  1757. RelationshipService::refresh($pid, $id);
  1758. }
  1759. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  1760. $res = $this->fractal->createData($resource)->toArray();
  1761. return $this->json($res);
  1762. }
  1763. /**
  1764. * GET /api/v1/notifications
  1765. *
  1766. *
  1767. * @return NotificationTransformer
  1768. */
  1769. public function accountNotifications(Request $request)
  1770. {
  1771. abort_if(!$request->user(), 403);
  1772. $this->validate($request, [
  1773. 'limit' => 'nullable|integer|min:1|max:100',
  1774. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1775. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1776. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1777. ]);
  1778. $pid = $request->user()->profile_id;
  1779. $limit = $request->input('limit', 20);
  1780. $since = $request->input('since_id');
  1781. $min = $request->input('min_id');
  1782. $max = $request->input('max_id');
  1783. if(!$since && !$min && !$max) {
  1784. $min = 1;
  1785. }
  1786. $maxId = null;
  1787. $minId = null;
  1788. if($max) {
  1789. $res = NotificationService::getMaxMastodon($pid, $max, $limit);
  1790. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1791. if(!empty($ids)) {
  1792. $maxId = max($ids);
  1793. $minId = min($ids);
  1794. }
  1795. } else {
  1796. $res = NotificationService::getMinMastodon($pid, $min ?? $since, $limit);
  1797. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1798. if(!empty($ids)) {
  1799. $maxId = max($ids);
  1800. $minId = min($ids);
  1801. }
  1802. }
  1803. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1804. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1805. NotificationService::warmCache($pid, 400, true);
  1806. }
  1807. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1808. if($minId == $maxId) {
  1809. $minId = null;
  1810. }
  1811. if($maxId) {
  1812. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1813. }
  1814. if($minId) {
  1815. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1816. }
  1817. if($maxId && $minId) {
  1818. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1819. }
  1820. $headers = isset($link) ? ['Link' => $link] : [];
  1821. return $this->json($res, 200, $headers);
  1822. }
  1823. /**
  1824. * GET /api/v1/timelines/home
  1825. *
  1826. *
  1827. * @return StatusTransformer
  1828. */
  1829. public function timelineHome(Request $request)
  1830. {
  1831. $this->validate($request,[
  1832. 'page' => 'sometimes|integer|max:40',
  1833. 'min_id' => 'sometimes|integer|min:0|max:' . PHP_INT_MAX,
  1834. 'max_id' => 'sometimes|integer|min:0|max:' . PHP_INT_MAX,
  1835. 'limit' => 'sometimes|integer|min:1|max:100',
  1836. 'include_reblogs' => 'sometimes',
  1837. ]);
  1838. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1839. $page = $request->input('page');
  1840. $min = $request->input('min_id');
  1841. $max = $request->input('max_id');
  1842. $limit = $request->input('limit') ?? 20;
  1843. $pid = $request->user()->profile_id;
  1844. $includeReblogs = $request->filled('include_reblogs');
  1845. $nullFields = $includeReblogs ?
  1846. ['in_reply_to_id'] :
  1847. ['in_reply_to_id', 'reblog_of_id'];
  1848. $inTypes = $includeReblogs ?
  1849. ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album', 'share'] :
  1850. ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'];
  1851. $following = Cache::remember('profile:following:'.$pid, 1209600, function() use($pid) {
  1852. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1853. return $following->push($pid)->toArray();
  1854. });
  1855. if($min || $max) {
  1856. $dir = $min ? '>' : '<';
  1857. $id = $min ?? $max;
  1858. $res = Status::select(
  1859. 'id',
  1860. 'profile_id',
  1861. 'type',
  1862. 'visibility',
  1863. 'in_reply_to_id',
  1864. 'reblog_of_id'
  1865. )
  1866. ->where('id', $dir, $id)
  1867. ->whereNull($nullFields)
  1868. ->whereIntegerInRaw('profile_id', $following)
  1869. ->whereIn('type', $inTypes)
  1870. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1871. ->orderByDesc('id')
  1872. ->take(($limit * 2))
  1873. ->get()
  1874. ->map(function($s) use($pid, $napi) {
  1875. try {
  1876. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  1877. if(!$account) {
  1878. return false;
  1879. }
  1880. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1881. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1882. return false;
  1883. }
  1884. } catch(\Exception $e) {
  1885. return false;
  1886. }
  1887. $status['account'] = $account;
  1888. if($pid) {
  1889. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1890. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1891. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  1892. }
  1893. return $status;
  1894. })
  1895. ->filter(function($status) {
  1896. return $status && isset($status['account']);
  1897. })
  1898. ->map(function($status) use($pid) {
  1899. if(!empty($status['reblog'])) {
  1900. $status['reblog']['favourited'] = (bool) LikeService::liked($pid, $status['reblog']['id']);
  1901. $status['reblog']['reblogged'] = (bool) ReblogService::get($pid, $status['reblog']['id']);
  1902. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  1903. }
  1904. return $status;
  1905. })
  1906. ->take($limit)
  1907. ->values();
  1908. } else {
  1909. $res = Status::select(
  1910. 'id',
  1911. 'profile_id',
  1912. 'type',
  1913. 'visibility',
  1914. 'in_reply_to_id',
  1915. 'reblog_of_id',
  1916. )
  1917. ->whereNull($nullFields)
  1918. ->whereIntegerInRaw('profile_id', $following)
  1919. ->whereIn('type', $inTypes)
  1920. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1921. ->orderByDesc('id')
  1922. ->take(($limit * 2))
  1923. ->get()
  1924. ->map(function($s) use($pid, $napi) {
  1925. try {
  1926. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  1927. if(!$account) {
  1928. return false;
  1929. }
  1930. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1931. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1932. return false;
  1933. }
  1934. } catch(\Exception $e) {
  1935. return false;
  1936. }
  1937. $status['account'] = $account;
  1938. if($pid) {
  1939. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1940. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1941. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  1942. }
  1943. return $status;
  1944. })
  1945. ->filter(function($status) {
  1946. return $status && isset($status['account']);
  1947. })
  1948. ->map(function($status) use($pid) {
  1949. if(!empty($status['reblog'])) {
  1950. $status['reblog']['favourited'] = (bool) LikeService::liked($pid, $status['reblog']['id']);
  1951. $status['reblog']['reblogged'] = (bool) ReblogService::get($pid, $status['reblog']['id']);
  1952. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  1953. }
  1954. return $status;
  1955. })
  1956. ->take($limit)
  1957. ->values();
  1958. }
  1959. $baseUrl = config('app.url') . '/api/v1/timelines/home?limit=' . $limit . '&';
  1960. $minId = $res->map(function($s) {
  1961. return ['id' => $s['id']];
  1962. })->min('id');
  1963. $maxId = $res->map(function($s) {
  1964. return ['id' => $s['id']];
  1965. })->max('id');
  1966. if($minId == $maxId) {
  1967. $minId = null;
  1968. }
  1969. if($maxId) {
  1970. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1971. }
  1972. if($minId) {
  1973. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1974. }
  1975. if($maxId && $minId) {
  1976. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1977. }
  1978. $headers = isset($link) ? ['Link' => $link] : [];
  1979. return $this->json($res->toArray(), 200, $headers);
  1980. }
  1981. /**
  1982. * GET /api/v1/timelines/public
  1983. *
  1984. *
  1985. * @return StatusTransformer
  1986. */
  1987. public function timelinePublic(Request $request)
  1988. {
  1989. $this->validate($request,[
  1990. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1991. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1992. 'limit' => 'nullable|integer|max:100',
  1993. 'remote' => 'sometimes',
  1994. 'local' => 'sometimes'
  1995. ]);
  1996. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1997. $min = $request->input('min_id');
  1998. $max = $request->input('max_id');
  1999. $limit = $request->input('limit') ?? 20;
  2000. $user = $request->user();
  2001. $remote = ($request->has('remote') && $request->input('remote') == true) || ($request->filled('local') && $request->input('local') != true);
  2002. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  2003. if((!$request->has('local') || $remote) && config('instance.timeline.network.cached')) {
  2004. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function() {
  2005. if(NetworkTimelineService::count() == 0) {
  2006. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  2007. }
  2008. });
  2009. if ($max) {
  2010. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  2011. } else if ($min) {
  2012. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  2013. } else {
  2014. $feed = NetworkTimelineService::get(0, $limit + 5);
  2015. }
  2016. } else {
  2017. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  2018. if(PublicTimelineService::count() == 0) {
  2019. PublicTimelineService::warmCache(true, 400);
  2020. }
  2021. });
  2022. if ($max) {
  2023. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  2024. } else if ($min) {
  2025. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  2026. } else {
  2027. $feed = PublicTimelineService::get(0, $limit + 5);
  2028. }
  2029. }
  2030. $res = collect($feed)
  2031. ->filter(function($k) use($min, $max) {
  2032. if(!$min && !$max) {
  2033. return true;
  2034. }
  2035. if($min) {
  2036. return $min != $k;
  2037. }
  2038. if($max) {
  2039. return $max != $k;
  2040. }
  2041. })
  2042. ->map(function($k) use($user, $napi) {
  2043. try {
  2044. $status = $napi ? StatusService::get($k) : StatusService::getMastodon($k);
  2045. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  2046. return false;
  2047. }
  2048. } catch(\Exception $e) {
  2049. return false;
  2050. }
  2051. $account = $napi ? AccountService::get($status['account']['id'], true) : AccountService::getMastodon($status['account']['id'], true);
  2052. if(!$account) {
  2053. return false;
  2054. }
  2055. $status['account'] = $account;
  2056. if($user) {
  2057. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  2058. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  2059. $status['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $status['id']);
  2060. }
  2061. return $status;
  2062. })
  2063. ->filter(function($s) use($filtered) {
  2064. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  2065. })
  2066. ->take($limit)
  2067. ->values();
  2068. $baseUrl = config('app.url') . '/api/v1/timelines/public?limit=' . $limit . '&';
  2069. if($remote) {
  2070. $baseUrl .= 'remote=1&';
  2071. }
  2072. $minId = $res->map(function($s) {
  2073. return ['id' => $s['id']];
  2074. })->min('id');
  2075. $maxId = $res->map(function($s) {
  2076. return ['id' => $s['id']];
  2077. })->max('id');
  2078. if($minId == $maxId) {
  2079. $minId = null;
  2080. }
  2081. if($maxId) {
  2082. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2083. }
  2084. if($minId) {
  2085. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2086. }
  2087. if($maxId && $minId) {
  2088. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2089. }
  2090. $headers = isset($link) ? ['Link' => $link] : [];
  2091. return $this->json($res->toArray(), 200, $headers);
  2092. }
  2093. /**
  2094. * GET /api/v1/conversations
  2095. *
  2096. * Not implemented
  2097. *
  2098. * @return array
  2099. */
  2100. public function conversations(Request $request)
  2101. {
  2102. abort_if(!$request->user(), 403);
  2103. $this->validate($request, [
  2104. 'limit' => 'min:1|max:40',
  2105. 'scope' => 'nullable|in:inbox,sent,requests'
  2106. ]);
  2107. $limit = $request->input('limit', 20);
  2108. $scope = $request->input('scope', 'inbox');
  2109. $pid = $request->user()->profile_id;
  2110. if(config('database.default') == 'pgsql') {
  2111. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  2112. return $q->whereIsHidden(false)->where('to_id', $pid)->orWhere('from_id', $pid);
  2113. })
  2114. ->when($scope === 'sent', function($q, $scope) use($pid) {
  2115. return $q->whereFromId($pid)->groupBy(['to_id', 'id']);
  2116. })
  2117. ->when($scope === 'requests', function($q, $scope) use($pid) {
  2118. return $q->whereToId($pid)->whereIsHidden(true);
  2119. });
  2120. } else {
  2121. $dms = Conversation::when($scope === 'inbox', function($q, $scope) use($pid) {
  2122. return $q->whereIsHidden(false)
  2123. ->where('to_id', $pid)
  2124. ->orWhere('from_id', $pid)
  2125. ->orderByDesc('status_id')
  2126. ->groupBy(['to_id', 'from_id']);
  2127. })
  2128. ->when($scope === 'sent', function($q, $scope) use($pid) {
  2129. return $q->whereFromId($pid)->groupBy('to_id');
  2130. })
  2131. ->when($scope === 'requests', function($q, $scope) use($pid) {
  2132. return $q->whereToId($pid)->whereIsHidden(true);
  2133. });
  2134. }
  2135. $dms = $dms->orderByDesc('status_id')
  2136. ->simplePaginate($limit)
  2137. ->map(function($dm) use($pid) {
  2138. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  2139. $res = [
  2140. 'id' => $dm->id,
  2141. 'unread' => false,
  2142. 'accounts' => [
  2143. AccountService::getMastodon($from, true)
  2144. ],
  2145. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  2146. ];
  2147. return $res;
  2148. })
  2149. ->filter(function($dm) {
  2150. if(!$dm || empty($dm['last_status']) || !isset($dm['accounts']) || !count($dm['accounts']) || !isset($dm['accounts'][0]) || !isset($dm['accounts'][0]['id'])) {
  2151. return false;
  2152. }
  2153. return true;
  2154. })
  2155. ->unique(function($item, $key) {
  2156. return $item['accounts'][0]['id'];
  2157. })
  2158. ->values();
  2159. return $this->json($dms);
  2160. }
  2161. /**
  2162. * GET /api/v1/statuses/{id}
  2163. *
  2164. * @param integer $id
  2165. *
  2166. * @return StatusTransformer
  2167. */
  2168. public function statusById(Request $request, $id)
  2169. {
  2170. abort_if(!$request->user(), 403);
  2171. $pid = $request->user()->profile_id;
  2172. $res = $request->has(self::PF_API_ENTITY_KEY) ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2173. if(!$res || !isset($res['visibility'])) {
  2174. abort(404);
  2175. }
  2176. $scope = $res['visibility'];
  2177. if(!in_array($scope, ['public', 'unlisted'])) {
  2178. if($scope === 'private') {
  2179. if(intval($res['account']['id']) !== intval($pid)) {
  2180. abort_unless(FollowerService::follows($pid, $res['account']['id']), 403);
  2181. }
  2182. } else {
  2183. abort(400, 'Invalid request');
  2184. }
  2185. }
  2186. if(!empty($res['reblog']) && isset($res['reblog']['id'])) {
  2187. $res['reblog']['favourited'] = (bool) LikeService::liked($pid, $res['reblog']['id']);
  2188. $res['reblog']['reblogged'] = (bool) ReblogService::get($pid, $res['reblog']['id']);
  2189. $res['reblog']['bookmarked'] = BookmarkService::get($pid, $res['reblog']['id']);
  2190. }
  2191. $res['favourited'] = LikeService::liked($pid, $res['id']);
  2192. $res['reblogged'] = ReblogService::get($pid, $res['id']);
  2193. $res['bookmarked'] = BookmarkService::get($pid, $res['id']);
  2194. return $this->json($res);
  2195. }
  2196. /**
  2197. * GET /api/v1/statuses/{id}/context
  2198. *
  2199. * @param integer $id
  2200. *
  2201. * @return StatusTransformer
  2202. */
  2203. public function statusContext(Request $request, $id)
  2204. {
  2205. abort_if(!$request->user(), 403);
  2206. $user = $request->user();
  2207. $pid = $user->profile_id;
  2208. $status = StatusService::getMastodon($id, false);
  2209. if(!$status || !isset($status['account'])) {
  2210. return response('', 404);
  2211. }
  2212. if(intval($status['account']['id']) !== intval($user->profile_id)) {
  2213. if($status['visibility'] == 'private') {
  2214. if(!FollowerService::follows($user->profile_id, $status['account']['id'])) {
  2215. return response('', 404);
  2216. }
  2217. } else {
  2218. if(!in_array($status['visibility'], ['public','unlisted'])) {
  2219. return response('', 404);
  2220. }
  2221. }
  2222. }
  2223. $ancestors = [];
  2224. $descendants = [];
  2225. if($status['in_reply_to_id']) {
  2226. $ancestors[] = StatusService::getMastodon($status['in_reply_to_id'], false);
  2227. }
  2228. if($status['replies_count']) {
  2229. $filters = UserFilterService::filters($pid);
  2230. $descendants = DB::table('statuses')
  2231. ->where('in_reply_to_id', $id)
  2232. ->limit(20)
  2233. ->pluck('id')
  2234. ->map(function($sid) {
  2235. return StatusService::getMastodon($sid, false);
  2236. })
  2237. ->filter(function($post) use($filters) {
  2238. return $post && isset($post['account'], $post['account']['id']) && !in_array($post['account']['id'], $filters);
  2239. })
  2240. ->map(function($status) use($pid) {
  2241. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2242. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2243. return $status;
  2244. })
  2245. ->values();
  2246. }
  2247. $res = [
  2248. 'ancestors' => $ancestors,
  2249. 'descendants' => $descendants
  2250. ];
  2251. return $this->json($res);
  2252. }
  2253. /**
  2254. * GET /api/v1/statuses/{id}/card
  2255. *
  2256. * @param integer $id
  2257. *
  2258. * @return StatusTransformer
  2259. */
  2260. public function statusCard(Request $request, $id)
  2261. {
  2262. abort_if(!$request->user(), 403);
  2263. $res = [];
  2264. return response()->json($res);
  2265. }
  2266. /**
  2267. * GET /api/v1/statuses/{id}/reblogged_by
  2268. *
  2269. * @param integer $id
  2270. *
  2271. * @return AccountTransformer
  2272. */
  2273. public function statusRebloggedBy(Request $request, $id)
  2274. {
  2275. abort_if(!$request->user(), 403);
  2276. $this->validate($request, [
  2277. 'limit' => 'sometimes|integer|min:1|max:80'
  2278. ]);
  2279. $limit = $request->input('limit', 10);
  2280. $user = $request->user();
  2281. $pid = $user->profile_id;
  2282. $status = Status::findOrFail($id);
  2283. $account = AccountService::get($status->profile_id, true);
  2284. abort_if(!$account, 404);
  2285. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2286. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2287. abort_if(
  2288. !$status->type ||
  2289. !in_array($status->type, ['photo','photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2290. 404,
  2291. );
  2292. if(!$author) {
  2293. if($status->scope == 'private') {
  2294. abort_if(!FollowerService::follows($pid, $status->profile_id), 403);
  2295. } else {
  2296. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2297. }
  2298. if($request->has('cursor')) {
  2299. return $this->json([]);
  2300. }
  2301. }
  2302. $res = Status::where('reblog_of_id', $status->id)
  2303. ->orderByDesc('id')
  2304. ->cursorPaginate($limit)
  2305. ->withQueryString();
  2306. if(!$res) {
  2307. return $this->json([]);
  2308. }
  2309. $headers = [];
  2310. if($author && $res->hasPages()) {
  2311. $links = '';
  2312. if($res->onFirstPage()) {
  2313. if($res->nextPageUrl()) {
  2314. $links = '<' . $res->nextPageUrl() .'>; rel="prev"';
  2315. }
  2316. } else {
  2317. if($res->previousPageUrl()) {
  2318. $links = '<' . $res->previousPageUrl() .'>; rel="next"';
  2319. }
  2320. if($res->nextPageUrl()) {
  2321. if(!empty($links)) {
  2322. $links .= ', ';
  2323. }
  2324. $links .= '<' . $res->nextPageUrl() .'>; rel="prev"';
  2325. }
  2326. }
  2327. $headers = ['Link' => $links];
  2328. }
  2329. $res = $res->map(function($status) use($pid, $napi) {
  2330. $account = $napi ? AccountService::get($status->profile_id, true) : AccountService::getMastodon($status->profile_id, true);
  2331. if(!$account) {
  2332. return false;
  2333. }
  2334. if($napi) {
  2335. $account['follows'] = $status->profile_id == $pid ? null : FollowerService::follows($pid, $status->profile_id);
  2336. }
  2337. return $account;
  2338. })
  2339. ->filter(function($account) {
  2340. return $account && isset($account['id']);
  2341. })
  2342. ->values();
  2343. return $this->json($res, 200, $headers);
  2344. }
  2345. /**
  2346. * GET /api/v1/statuses/{id}/favourited_by
  2347. *
  2348. * @param integer $id
  2349. *
  2350. * @return AccountTransformer
  2351. */
  2352. public function statusFavouritedBy(Request $request, $id)
  2353. {
  2354. abort_if(!$request->user(), 403);
  2355. $this->validate($request, [
  2356. 'limit' => 'nullable|integer|min:1|max:80'
  2357. ]);
  2358. $limit = $request->input('limit', 10);
  2359. $user = $request->user();
  2360. $pid = $user->profile_id;
  2361. $status = Status::findOrFail($id);
  2362. $account = AccountService::get($status->profile_id, true);
  2363. abort_if(!$account, 404);
  2364. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2365. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2366. abort_if(
  2367. !$status->type ||
  2368. !in_array($status->type, ['photo','photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2369. 404,
  2370. );
  2371. if(!$author) {
  2372. if($status->scope == 'private') {
  2373. abort_if(!FollowerService::follows($pid, $status->profile_id), 403);
  2374. } else {
  2375. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2376. }
  2377. if($request->has('cursor')) {
  2378. return $this->json([]);
  2379. }
  2380. }
  2381. $res = Like::where('status_id', $status->id)
  2382. ->orderByDesc('id')
  2383. ->cursorPaginate($limit)
  2384. ->withQueryString();
  2385. if(!$res) {
  2386. return $this->json([]);
  2387. }
  2388. $headers = [];
  2389. if($author && $res->hasPages()) {
  2390. $links = '';
  2391. if($res->onFirstPage()) {
  2392. if($res->nextPageUrl()) {
  2393. $links = '<' . $res->nextPageUrl() .'>; rel="prev"';
  2394. }
  2395. } else {
  2396. if($res->previousPageUrl()) {
  2397. $links = '<' . $res->previousPageUrl() .'>; rel="next"';
  2398. }
  2399. if($res->nextPageUrl()) {
  2400. if(!empty($links)) {
  2401. $links .= ', ';
  2402. }
  2403. $links .= '<' . $res->nextPageUrl() .'>; rel="prev"';
  2404. }
  2405. }
  2406. $headers = ['Link' => $links];
  2407. }
  2408. $res = $res->map(function($like) use($pid, $napi) {
  2409. $account = $napi ? AccountService::get($like->profile_id, true) : AccountService::getMastodon($like->profile_id, true);
  2410. if(!$account) {
  2411. return false;
  2412. }
  2413. if($napi) {
  2414. $account['follows'] = $like->profile_id == $pid ? null : FollowerService::follows($pid, $like->profile_id);
  2415. }
  2416. return $account;
  2417. })
  2418. ->filter(function($account) {
  2419. return $account && isset($account['id']);
  2420. })
  2421. ->values();
  2422. return $this->json($res, 200, $headers);
  2423. }
  2424. /**
  2425. * POST /api/v1/statuses
  2426. *
  2427. *
  2428. * @return StatusTransformer
  2429. */
  2430. public function statusCreate(Request $request)
  2431. {
  2432. abort_if(!$request->user(), 403);
  2433. $this->validate($request, [
  2434. 'status' => 'nullable|string',
  2435. 'in_reply_to_id' => 'nullable',
  2436. 'media_ids' => 'sometimes|array|max:' . config_cache('pixelfed.max_album_length'),
  2437. 'sensitive' => 'nullable',
  2438. 'visibility' => 'string|in:private,unlisted,public',
  2439. 'spoiler_text' => 'sometimes|max:140',
  2440. 'place_id' => 'sometimes|integer|min:1|max:128769',
  2441. 'collection_ids' => 'sometimes|array|max:3',
  2442. 'comments_disabled' => 'sometimes|boolean',
  2443. ]);
  2444. if($request->hasHeader('idempotency-key')) {
  2445. $key = 'pf:api:v1:status:idempotency-key:' . $request->user()->id . ':' . hash('sha1', $request->header('idempotency-key'));
  2446. $exists = Cache::has($key);
  2447. abort_if($exists, 400, 'Duplicate idempotency key.');
  2448. Cache::put($key, 1, 3600);
  2449. }
  2450. if(config('costar.enabled') == true) {
  2451. $blockedKeywords = config('costar.keyword.block');
  2452. if($blockedKeywords !== null && $request->status) {
  2453. $keywords = config('costar.keyword.block');
  2454. foreach($keywords as $kw) {
  2455. if(Str::contains($request->status, $kw) == true) {
  2456. abort(400, 'Invalid object. Contains banned keyword.');
  2457. }
  2458. }
  2459. }
  2460. }
  2461. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  2462. abort(403, 'Empty statuses are not allowed');
  2463. }
  2464. $ids = $request->input('media_ids');
  2465. $in_reply_to_id = $request->input('in_reply_to_id');
  2466. $user = $request->user();
  2467. $profile = $user->profile;
  2468. $limitKey = 'compose:rate-limit:store:' . $user->id;
  2469. $limitTtl = now()->addMinutes(15);
  2470. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  2471. $dailyLimit = Status::whereProfileId($user->profile_id)
  2472. ->whereNull('in_reply_to_id')
  2473. ->whereNull('reblog_of_id')
  2474. ->where('created_at', '>', now()->subDays(1))
  2475. ->count();
  2476. return $dailyLimit >= 1000;
  2477. });
  2478. abort_if($limitReached == true, 429);
  2479. $visibility = $profile->is_private ? 'private' : (
  2480. $profile->unlisted == true &&
  2481. $request->input('visibility', 'public') == 'public' ?
  2482. 'unlisted' :
  2483. $request->input('visibility', 'public'));
  2484. if($user->last_active_at == null) {
  2485. return [];
  2486. }
  2487. $content = strip_tags($request->input('status'));
  2488. $rendered = Autolink::create()->autolink($content);
  2489. $cw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  2490. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  2491. if($in_reply_to_id) {
  2492. $parent = Status::findOrFail($in_reply_to_id);
  2493. if($parent->comments_disabled) {
  2494. return $this->json("Comments have been disabled on this post", 422);
  2495. }
  2496. $blocks = UserFilterService::blocks($parent->profile_id);
  2497. abort_if(in_array($profile->id, $blocks), 422, 'Cannot reply to this post at this time.');
  2498. $status = new Status;
  2499. $status->caption = $content;
  2500. $status->rendered = $rendered;
  2501. $status->scope = $visibility;
  2502. $status->visibility = $visibility;
  2503. $status->profile_id = $user->profile_id;
  2504. $status->is_nsfw = $cw;
  2505. $status->cw_summary = $spoilerText;
  2506. $status->in_reply_to_id = $parent->id;
  2507. $status->in_reply_to_profile_id = $parent->profile_id;
  2508. $status->save();
  2509. StatusService::del($parent->id);
  2510. Cache::forget('status:replies:all:' . $parent->id);
  2511. }
  2512. if($ids) {
  2513. if(Media::whereUserId($user->id)
  2514. ->whereNull('status_id')
  2515. ->find($ids)
  2516. ->count() == 0
  2517. ) {
  2518. abort(400, 'Invalid media_ids');
  2519. }
  2520. if(!$in_reply_to_id) {
  2521. $status = new Status;
  2522. $status->caption = $content;
  2523. $status->rendered = $rendered;
  2524. $status->profile_id = $user->profile_id;
  2525. $status->is_nsfw = $cw;
  2526. $status->cw_summary = $spoilerText;
  2527. $status->scope = 'draft';
  2528. $status->visibility = 'draft';
  2529. if($request->has('place_id')) {
  2530. $status->place_id = $request->input('place_id');
  2531. }
  2532. $status->save();
  2533. }
  2534. $mimes = [];
  2535. foreach($ids as $k => $v) {
  2536. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  2537. continue;
  2538. }
  2539. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  2540. if($m->profile_id !== $user->profile_id || $m->status_id) {
  2541. abort(403, 'Invalid media id');
  2542. }
  2543. $m->order = $k + 1;
  2544. $m->status_id = $status->id;
  2545. $m->save();
  2546. array_push($mimes, $m->mime);
  2547. }
  2548. if(empty($mimes)) {
  2549. $status->delete();
  2550. abort(400, 'Invalid media ids');
  2551. }
  2552. if($request->has('comments_disabled') && $request->input('comments_disabled')) {
  2553. $status->comments_disabled = true;
  2554. }
  2555. $status->scope = $visibility;
  2556. $status->visibility = $visibility;
  2557. $status->type = StatusController::mimeTypeCheck($mimes);
  2558. $status->save();
  2559. }
  2560. if(!$status) {
  2561. abort(500, 'An error occured.');
  2562. }
  2563. NewStatusPipeline::dispatch($status);
  2564. if($status->in_reply_to_id) {
  2565. CommentPipeline::dispatch($parent, $status);
  2566. }
  2567. Cache::forget('user:account:id:'.$user->id);
  2568. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  2569. Cache::forget('profile:status_count:'.$user->profile_id);
  2570. Cache::forget($user->storageUsedKey());
  2571. Cache::forget('profile:embed:' . $status->profile_id);
  2572. Cache::forget($limitKey);
  2573. if($request->has('collection_ids') && $ids) {
  2574. $collections = Collection::whereProfileId($user->profile_id)
  2575. ->find($request->input('collection_ids'))
  2576. ->each(function($collection) use($status) {
  2577. $count = $collection->items()->count();
  2578. $item = CollectionItem::firstOrCreate([
  2579. 'collection_id' => $collection->id,
  2580. 'object_type' => 'App\Status',
  2581. 'object_id' => $status->id
  2582. ],[
  2583. 'order' => $count,
  2584. ]);
  2585. CollectionService::addItem(
  2586. $collection->id,
  2587. $status->id,
  2588. $count
  2589. );
  2590. $collection->updated_at = now();
  2591. $collection->save();
  2592. CollectionService::setCollection($collection->id, $collection);
  2593. });
  2594. }
  2595. $res = StatusService::getMastodon($status->id, false);
  2596. $res['favourited'] = false;
  2597. $res['language'] = 'en';
  2598. $res['bookmarked'] = false;
  2599. $res['card'] = null;
  2600. return $this->json($res);
  2601. }
  2602. /**
  2603. * DELETE /api/v1/statuses
  2604. *
  2605. * @param integer $id
  2606. *
  2607. * @return null
  2608. */
  2609. public function statusDelete(Request $request, $id)
  2610. {
  2611. abort_if(!$request->user(), 403);
  2612. $status = Status::whereProfileId($request->user()->profile->id)
  2613. ->findOrFail($id);
  2614. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2615. Cache::forget('profile:status_count:'.$status->profile_id);
  2616. StatusDelete::dispatch($status);
  2617. $res = $this->fractal->createData($resource)->toArray();
  2618. $res['text'] = $res['content'];
  2619. unset($res['content']);
  2620. return $this->json($res);
  2621. }
  2622. /**
  2623. * POST /api/v1/statuses/{id}/reblog
  2624. *
  2625. * @param integer $id
  2626. *
  2627. * @return StatusTransformer
  2628. */
  2629. public function statusShare(Request $request, $id)
  2630. {
  2631. abort_if(!$request->user(), 403);
  2632. $user = $request->user();
  2633. $status = Status::whereScope('public')->findOrFail($id);
  2634. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2635. if($status->scope == 'private') {
  2636. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2637. } else {
  2638. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2639. }
  2640. $blocks = UserFilterService::blocks($status->profile_id);
  2641. if($blocks && in_array($user->profile_id, $blocks)) {
  2642. abort(422);
  2643. }
  2644. }
  2645. $share = Status::firstOrCreate([
  2646. 'profile_id' => $user->profile_id,
  2647. 'reblog_of_id' => $status->id,
  2648. 'type' => 'share',
  2649. 'in_reply_to_profile_id' => $status->profile_id,
  2650. 'scope' => 'public',
  2651. 'visibility' => 'public'
  2652. ]);
  2653. SharePipeline::dispatch($share)->onQueue('low');
  2654. StatusService::del($status->id);
  2655. ReblogService::add($user->profile_id, $status->id);
  2656. $res = StatusService::getMastodon($status->id);
  2657. $res['reblogged'] = true;
  2658. return $this->json($res);
  2659. }
  2660. /**
  2661. * POST /api/v1/statuses/{id}/unreblog
  2662. *
  2663. * @param integer $id
  2664. *
  2665. * @return StatusTransformer
  2666. */
  2667. public function statusUnshare(Request $request, $id)
  2668. {
  2669. abort_if(!$request->user(), 403);
  2670. $user = $request->user();
  2671. $status = Status::whereScope('public')->findOrFail($id);
  2672. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2673. if($status->scope == 'private') {
  2674. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2675. } else {
  2676. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2677. }
  2678. }
  2679. $reblog = Status::whereProfileId($user->profile_id)
  2680. ->whereReblogOfId($status->id)
  2681. ->first();
  2682. if(!$reblog) {
  2683. $res = StatusService::getMastodon($status->id);
  2684. $res['reblogged'] = false;
  2685. return $this->json($res);
  2686. }
  2687. UndoSharePipeline::dispatch($reblog)->onQueue('low');
  2688. ReblogService::del($user->profile_id, $status->id);
  2689. $res = StatusService::getMastodon($status->id);
  2690. $res['reblogged'] = false;
  2691. return $this->json($res);
  2692. }
  2693. /**
  2694. * GET /api/v1/timelines/tag/{hashtag}
  2695. *
  2696. * @param string $hashtag
  2697. *
  2698. * @return StatusTransformer
  2699. */
  2700. public function timelineHashtag(Request $request, $hashtag)
  2701. {
  2702. abort_if(!$request->user(), 403);
  2703. $this->validate($request,[
  2704. 'page' => 'nullable|integer|max:40',
  2705. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2706. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2707. 'limit' => 'nullable|integer|max:100',
  2708. 'only_media' => 'sometimes|boolean',
  2709. '_pe' => 'sometimes'
  2710. ]);
  2711. if(config('database.default') === 'pgsql') {
  2712. $tag = Hashtag::where('name', 'ilike', $hashtag)
  2713. ->orWhere('slug', 'ilike', $hashtag)
  2714. ->first();
  2715. } else {
  2716. $tag = Hashtag::whereName($hashtag)
  2717. ->orWhere('slug', $hashtag)
  2718. ->first();
  2719. }
  2720. if(!$tag) {
  2721. return response()->json([]);
  2722. }
  2723. if($tag->is_banned == true) {
  2724. return $this->json([]);
  2725. }
  2726. $min = $request->input('min_id');
  2727. $max = $request->input('max_id');
  2728. $limit = $request->input('limit', 20);
  2729. $onlyMedia = $request->input('only_media', true);
  2730. $pe = $request->has(self::PF_API_ENTITY_KEY);
  2731. if($min || $max) {
  2732. $minMax = SnowflakeService::byDate(now()->subMonths(6));
  2733. if($min && intval($min) < $minMax) {
  2734. return [];
  2735. }
  2736. if($max && intval($max) < $minMax) {
  2737. return [];
  2738. }
  2739. }
  2740. $filters = UserFilterService::filters($request->user()->profile_id);
  2741. if(!$min && !$max) {
  2742. $id = 1;
  2743. $dir = '>';
  2744. } else {
  2745. $dir = $min ? '>' : '<';
  2746. $id = $min ?? $max;
  2747. }
  2748. $res = StatusHashtag::whereHashtagId($tag->id)
  2749. ->whereStatusVisibility('public')
  2750. ->where('status_id', $dir, $id)
  2751. ->orderBy('status_id', 'desc')
  2752. ->limit($limit)
  2753. ->pluck('status_id')
  2754. ->map(function ($i) use($pe) {
  2755. return $pe ? StatusService::get($i) : StatusService::getMastodon($i);
  2756. })
  2757. ->filter(function($i) use($onlyMedia) {
  2758. if(!$i) {
  2759. return false;
  2760. }
  2761. if($onlyMedia && !isset($i['media_attachments']) || !count($i['media_attachments'])) {
  2762. return false;
  2763. }
  2764. return $i && isset($i['account']);
  2765. })
  2766. ->filter(function($i) use($filters) {
  2767. return !in_array($i['account']['id'], $filters);
  2768. })
  2769. ->values()
  2770. ->toArray();
  2771. return $this->json($res);
  2772. }
  2773. /**
  2774. * GET /api/v1/bookmarks
  2775. *
  2776. *
  2777. *
  2778. * @return StatusTransformer
  2779. */
  2780. public function bookmarks(Request $request)
  2781. {
  2782. abort_if(!$request->user(), 403);
  2783. $this->validate($request, [
  2784. 'limit' => 'nullable|integer|min:1|max:40',
  2785. 'max_id' => 'nullable|integer|min:0',
  2786. 'since_id' => 'nullable|integer|min:0',
  2787. 'min_id' => 'nullable|integer|min:0'
  2788. ]);
  2789. $pe = $request->has('_pe');
  2790. $pid = $request->user()->profile_id;
  2791. $limit = $request->input('limit') ?? 20;
  2792. $max_id = $request->input('max_id');
  2793. $since_id = $request->input('since_id');
  2794. $min_id = $request->input('min_id');
  2795. $dir = $min_id ? '>' : '<';
  2796. $id = $min_id ?? $max_id;
  2797. $bookmarkQuery = Bookmark::whereProfileId($pid)
  2798. ->orderByDesc('id')
  2799. ->cursorPaginate($limit);
  2800. $bookmarks = $bookmarkQuery->map(function($bookmark) use($pid, $pe) {
  2801. $status = $pe ? StatusService::get($bookmark->status_id, false) : StatusService::getMastodon($bookmark->status_id, false);
  2802. if($status) {
  2803. $status['bookmarked'] = true;
  2804. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2805. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2806. }
  2807. return $status;
  2808. })
  2809. ->filter()
  2810. ->values()
  2811. ->toArray();
  2812. $links = null;
  2813. $headers = [];
  2814. if($bookmarkQuery->nextCursor()) {
  2815. $links .= '<'.$bookmarkQuery->nextPageUrl().'&limit='.$limit.'>; rel="next"';
  2816. }
  2817. if($bookmarkQuery->previousCursor()) {
  2818. if($links != null) {
  2819. $links .= ', ';
  2820. }
  2821. $links .= '<'.$bookmarkQuery->previousPageUrl().'&limit='.$limit.'>; rel="prev"';
  2822. }
  2823. if($links) {
  2824. $headers = ['Link' => $links];
  2825. }
  2826. return $this->json($bookmarks, 200, $headers);
  2827. }
  2828. /**
  2829. * POST /api/v1/statuses/{id}/bookmark
  2830. *
  2831. *
  2832. *
  2833. * @return StatusTransformer
  2834. */
  2835. public function bookmarkStatus(Request $request, $id)
  2836. {
  2837. abort_if(!$request->user(), 403);
  2838. $status = Status::findOrFail($id);
  2839. $pid = $request->user()->profile_id;
  2840. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  2841. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2842. abort_if(!in_array($status->type, ['photo','photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  2843. if($status->scope == 'private') {
  2844. abort_if(
  2845. $pid !== $status->profile_id && !FollowerService::follows($pid, $status->profile_id),
  2846. 404,
  2847. 'Error: You cannot bookmark private posts from accounts you do not follow.'
  2848. );
  2849. }
  2850. Bookmark::firstOrCreate([
  2851. 'status_id' => $status->id,
  2852. 'profile_id' => $pid
  2853. ]);
  2854. BookmarkService::add($pid, $status->id);
  2855. $res = StatusService::getMastodon($status->id, false);
  2856. $res['bookmarked'] = true;
  2857. return $this->json($res);
  2858. }
  2859. /**
  2860. * POST /api/v1/statuses/{id}/unbookmark
  2861. *
  2862. *
  2863. *
  2864. * @return StatusTransformer
  2865. */
  2866. public function unbookmarkStatus(Request $request, $id)
  2867. {
  2868. abort_if(!$request->user(), 403);
  2869. $status = Status::findOrFail($id);
  2870. $pid = $request->user()->profile_id;
  2871. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  2872. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2873. abort_if(!in_array($status->type, ['photo','photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  2874. $bookmark = Bookmark::whereStatusId($status->id)
  2875. ->whereProfileId($pid)
  2876. ->first();
  2877. if($bookmark) {
  2878. BookmarkService::del($pid, $status->id);
  2879. $bookmark->delete();
  2880. }
  2881. $res = StatusService::getMastodon($status->id, false);
  2882. $res['bookmarked'] = false;
  2883. return $this->json($res);
  2884. }
  2885. /**
  2886. * GET /api/v1/discover/posts
  2887. *
  2888. *
  2889. * @return array
  2890. */
  2891. public function discoverPosts(Request $request)
  2892. {
  2893. abort_if(!$request->user(), 403);
  2894. $this->validate($request, [
  2895. 'limit' => 'integer|min:1|max:40'
  2896. ]);
  2897. $limit = $request->input('limit', 40);
  2898. $pid = $request->user()->profile_id;
  2899. $filters = UserFilterService::filters($pid);
  2900. $forYou = DiscoverService::getForYou();
  2901. $posts = $forYou->take(50)->map(function($post) {
  2902. return StatusService::getMastodon($post);
  2903. })
  2904. ->filter(function($post) use($filters) {
  2905. return $post &&
  2906. isset($post['account']) &&
  2907. isset($post['account']['id']) &&
  2908. !in_array($post['account']['id'], $filters);
  2909. })
  2910. ->take(12)
  2911. ->values();
  2912. return $this->json(compact('posts'));
  2913. }
  2914. /**
  2915. * GET /api/v2/statuses/{id}/replies
  2916. *
  2917. *
  2918. * @return array
  2919. */
  2920. public function statusReplies(Request $request, $id)
  2921. {
  2922. abort_if(!$request->user(), 403);
  2923. $this->validate($request, [
  2924. 'limit' => 'int|min:1|max:10',
  2925. 'sort' => 'in:all,newest,popular'
  2926. ]);
  2927. $limit = $request->input('limit', 3);
  2928. $pid = $request->user()->profile_id;
  2929. $status = StatusService::getMastodon($id, false);
  2930. abort_if(!$status, 404);
  2931. if($status['visibility'] == 'private') {
  2932. if($pid != $status['account']['id']) {
  2933. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  2934. }
  2935. }
  2936. $sortBy = $request->input('sort', 'all');
  2937. if($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  2938. if(!Cache::has('status:replies:all-rc:' . $id)) {
  2939. Cache::forget('status:replies:all:' . $id);
  2940. Cache::put('status:replies:all-rc:' . $id, true, 300);
  2941. }
  2942. }
  2943. if($sortBy == 'all' && !$request->has('cursor')) {
  2944. $ids = Cache::remember('status:replies:all:' . $id, 3600, function() use($id) {
  2945. return DB::table('statuses')
  2946. ->where('in_reply_to_id', $id)
  2947. ->orderBy('id')
  2948. ->cursorPaginate(3);
  2949. });
  2950. } else {
  2951. $ids = DB::table('statuses')
  2952. ->where('in_reply_to_id', $id)
  2953. ->when($sortBy, function($q, $sortBy) {
  2954. if($sortBy === 'all') {
  2955. return $q->orderBy('id');
  2956. }
  2957. if($sortBy === 'newest') {
  2958. return $q->orderByDesc('created_at');
  2959. }
  2960. if($sortBy === 'popular') {
  2961. return $q->orderByDesc('likes_count');
  2962. }
  2963. })
  2964. ->cursorPaginate($limit);
  2965. }
  2966. $filters = UserFilterService::filters($pid);
  2967. $data = $ids->filter(function($post) use($filters) {
  2968. return !in_array($post->profile_id, $filters);
  2969. })
  2970. ->map(function($post) use($pid) {
  2971. $status = StatusService::get($post->id, false);
  2972. if(!$status || !isset($status['id'])) {
  2973. return false;
  2974. }
  2975. $status['favourited'] = LikeService::liked($pid, $post->id);
  2976. return $status;
  2977. })
  2978. ->map(function($post) {
  2979. if(isset($post['account']) && isset($post['account']['id'])) {
  2980. $account = AccountService::get($post['account']['id'], true);
  2981. $post['account'] = $account;
  2982. }
  2983. return $post;
  2984. })
  2985. ->filter(function($post) {
  2986. return $post && isset($post['id']) && isset($post['account']) && isset($post['account']['id']);
  2987. })
  2988. ->values();
  2989. $res = [
  2990. 'data' => $data,
  2991. 'next' => $ids->nextPageUrl()
  2992. ];
  2993. return $this->json($res);
  2994. }
  2995. /**
  2996. * GET /api/v2/statuses/{id}/state
  2997. *
  2998. *
  2999. * @return array
  3000. */
  3001. public function statusState(Request $request, $id)
  3002. {
  3003. abort_if(!$request->user(), 403);
  3004. $status = Status::findOrFail($id);
  3005. $pid = $request->user()->profile_id;
  3006. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3007. return $this->json(StatusService::getState($status->id, $pid));
  3008. }
  3009. /**
  3010. * GET /api/v1.1/discover/accounts/popular
  3011. *
  3012. *
  3013. * @return array
  3014. */
  3015. public function discoverAccountsPopular(Request $request)
  3016. {
  3017. abort_if(!$request->user(), 403);
  3018. $pid = $request->user()->profile_id;
  3019. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 86400, function() {
  3020. return DB::table('profiles')
  3021. ->where('is_private', false)
  3022. ->whereNull('status')
  3023. ->orderByDesc('profiles.followers_count')
  3024. ->limit(20)
  3025. ->get();
  3026. });
  3027. $ids = $ids->map(function($profile) {
  3028. return AccountService::get($profile->id, true);
  3029. })
  3030. ->filter(function($profile) use($pid) {
  3031. return $profile && isset($profile['id']);
  3032. })
  3033. ->filter(function($profile) use($pid) {
  3034. return $profile['id'] != $pid;
  3035. })
  3036. ->map(function($profile) {
  3037. $ids = collect(ProfileStatusService::get($profile['id'], 0, 9))
  3038. ->map(function($id) {
  3039. return StatusService::get($id, true);
  3040. })
  3041. ->filter(function($post) {
  3042. return $post && isset($post['id']);
  3043. })
  3044. ->take(3)
  3045. ->values();
  3046. $profile['recent_posts'] = $ids;
  3047. return $profile;
  3048. })
  3049. ->take(6)
  3050. ->values();
  3051. return $this->json($ids);
  3052. }
  3053. /**
  3054. * GET /api/v1/preferences
  3055. *
  3056. *
  3057. * @return array
  3058. */
  3059. public function getPreferences(Request $request)
  3060. {
  3061. abort_if(!$request->user(), 403);
  3062. $pid = $request->user()->profile_id;
  3063. $account = AccountService::get($pid);
  3064. return $this->json([
  3065. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  3066. 'posting:default:sensitive' => false,
  3067. 'posting:default:language' => null,
  3068. 'reading:expand:media' => 'default',
  3069. 'reading:expand:spoilers' => false
  3070. ]);
  3071. }
  3072. /**
  3073. * GET /api/v1/trends
  3074. *
  3075. *
  3076. * @return array
  3077. */
  3078. public function getTrends(Request $request)
  3079. {
  3080. abort_if(!$request->user(), 403);
  3081. return $this->json([]);
  3082. }
  3083. /**
  3084. * GET /api/v1/announcements
  3085. *
  3086. *
  3087. * @return array
  3088. */
  3089. public function getAnnouncements(Request $request)
  3090. {
  3091. abort_if(!$request->user(), 403);
  3092. return $this->json([]);
  3093. }
  3094. /**
  3095. * GET /api/v1/markers
  3096. *
  3097. *
  3098. * @return array
  3099. */
  3100. public function getMarkers(Request $request)
  3101. {
  3102. abort_if(!$request->user(), 403);
  3103. $type = $request->input('timeline');
  3104. if(is_array($type)) {
  3105. $type = $type[0];
  3106. }
  3107. if(!$type || !in_array($type, ['home', 'notifications'])) {
  3108. return $this->json([]);
  3109. }
  3110. $pid = $request->user()->profile_id;
  3111. return $this->json(MarkerService::get($pid, $type));
  3112. }
  3113. /**
  3114. * POST /api/v1/markers
  3115. *
  3116. *
  3117. * @return array
  3118. */
  3119. public function setMarkers(Request $request)
  3120. {
  3121. abort_if(!$request->user(), 403);
  3122. $pid = $request->user()->profile_id;
  3123. $home = $request->input('home[last_read_id]');
  3124. $notifications = $request->input('notifications[last_read_id]');
  3125. if($home) {
  3126. return $this->json(MarkerService::set($pid, 'home', $home));
  3127. }
  3128. if($notifications) {
  3129. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  3130. }
  3131. return $this->json([]);
  3132. }
  3133. /**
  3134. * GET /api/v1/followed_tags
  3135. *
  3136. *
  3137. * @return array
  3138. */
  3139. public function getFollowedTags(Request $request)
  3140. {
  3141. abort_if(!$request->user(), 403);
  3142. $account = AccountService::get($request->user()->profile_id);
  3143. $this->validate($request, [
  3144. 'cursor' => 'sometimes',
  3145. 'limit' => 'sometimes|integer|min:1|max:200'
  3146. ]);
  3147. $limit = $request->input('limit', 100);
  3148. $res = HashtagFollow::whereProfileId($account['id'])
  3149. ->orderByDesc('id')
  3150. ->cursorPaginate($limit)->withQueryString();
  3151. $pagination = false;
  3152. $prevPage = $res->nextPageUrl();
  3153. $nextPage = $res->previousPageUrl();
  3154. if($nextPage && $prevPage) {
  3155. $pagination = '<' . $nextPage . '>; rel="next", <' . $prevPage . '>; rel="prev"';
  3156. } else if($nextPage && !$prevPage) {
  3157. $pagination = '<' . $nextPage . '>; rel="next"';
  3158. } else if(!$nextPage && $prevPage) {
  3159. $pagination = '<' . $prevPage . '>; rel="prev"';
  3160. }
  3161. if($pagination) {
  3162. return response()->json(FollowedTagResource::collection($res)->collection)
  3163. ->header('Link', $pagination);
  3164. }
  3165. return response()->json(FollowedTagResource::collection($res)->collection);
  3166. }
  3167. /**
  3168. * POST /api/v1/tags/:id/follow
  3169. *
  3170. *
  3171. * @return object
  3172. */
  3173. public function followHashtag(Request $request, $id)
  3174. {
  3175. abort_if(!$request->user(), 403);
  3176. $pid = $request->user()->profile_id;
  3177. $account = AccountService::get($pid);
  3178. $operator = config('database.default') == 'pgsql' ? 'ilike' : 'like';
  3179. $tag = Hashtag::where('name', $operator, $id)
  3180. ->orWhere('slug', $operator, $id)
  3181. ->first();
  3182. abort_if(!$tag, 422, 'Unknown hashtag');
  3183. abort_if(
  3184. HashtagFollow::whereProfileId($pid)->count() >= HashtagFollow::MAX_LIMIT,
  3185. 422,
  3186. 'You cannot follow more than ' . HashtagFollow::MAX_LIMIT . ' hashtags.'
  3187. );
  3188. $follows = HashtagFollow::updateOrCreate(
  3189. [
  3190. 'profile_id' => $account['id'],
  3191. 'hashtag_id' => $tag->id
  3192. ],
  3193. [
  3194. 'user_id' => $request->user()->id
  3195. ]
  3196. );
  3197. HashtagService::follow($pid, $tag->id);
  3198. return response()->json(FollowedTagResource::make($follows)->toArray($request));
  3199. }
  3200. /**
  3201. * POST /api/v1/tags/:id/unfollow
  3202. *
  3203. *
  3204. * @return object
  3205. */
  3206. public function unfollowHashtag(Request $request, $id)
  3207. {
  3208. abort_if(!$request->user(), 403);
  3209. $pid = $request->user()->profile_id;
  3210. $account = AccountService::get($pid);
  3211. $operator = config('database.default') == 'pgsql' ? 'ilike' : 'like';
  3212. $tag = Hashtag::where('name', $operator, $id)
  3213. ->orWhere('slug', $operator, $id)
  3214. ->first();
  3215. abort_if(!$tag, 422, 'Unknown hashtag');
  3216. $follows = HashtagFollow::whereProfileId($pid)
  3217. ->whereHashtagId($tag->id)
  3218. ->first();
  3219. if(!$follows) {
  3220. return [
  3221. 'name' => $tag->name,
  3222. 'url' => config('app.url') . '/i/web/hashtag/' . $tag->slug,
  3223. 'history' => [],
  3224. 'following' => false
  3225. ];
  3226. }
  3227. if($follows) {
  3228. HashtagService::unfollow($pid, $tag->id);
  3229. $follows->delete();
  3230. }
  3231. $res = FollowedTagResource::make($follows)->toArray($request);
  3232. $res['following'] = false;
  3233. return response()->json($res);
  3234. }
  3235. /**
  3236. * GET /api/v1/tags/:id
  3237. *
  3238. *
  3239. * @return object
  3240. */
  3241. public function getHashtag(Request $request, $id)
  3242. {
  3243. abort_if(!$request->user(), 403);
  3244. $pid = $request->user()->profile_id;
  3245. $account = AccountService::get($pid);
  3246. $operator = config('database.default') == 'pgsql' ? 'ilike' : 'like';
  3247. $tag = Hashtag::where('name', $operator, $id)
  3248. ->orWhere('slug', $operator, $id)
  3249. ->first();
  3250. if(!$tag) {
  3251. return [
  3252. 'name' => $id,
  3253. 'url' => config('app.url') . '/i/web/hashtag/' . $id,
  3254. 'history' => [],
  3255. 'following' => false
  3256. ];
  3257. }
  3258. $res = [
  3259. 'name' => $tag->name,
  3260. 'url' => config('app.url') . '/i/web/hashtag/' . $tag->slug,
  3261. 'history' => [],
  3262. 'following' => HashtagService::isFollowing($pid, $tag->id)
  3263. ];
  3264. if($request->has(self::PF_API_ENTITY_KEY)) {
  3265. $res['count'] = HashtagService::count($tag->id);
  3266. }
  3267. return $this->json($res);
  3268. }
  3269. }