AccountController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. <?php
  2. namespace app\Controllers;
  3. use app\Exceptions\FollowNotFoundException;
  4. use app\Exceptions\InvalidRequestException;
  5. use app\Exceptions\UnauthenticatedException;
  6. use app\Exceptions\VideoNotFoundException;
  7. use app\Hajeebtok;
  8. use app\Interfaces\IRouteController;
  9. use app\Logger;
  10. use app\Types\DatabaseObjects\Account;
  11. use app\Types\DatabaseObjects\Follow;
  12. use app\Types\DatabaseObjects\Link;
  13. use app\Types\DatabaseObjects\Session;
  14. use app\Types\LinkEnum;
  15. use Exception;
  16. use app\Exceptions\SecurityFaultException;
  17. use Mimey\MimeTypes;
  18. use Pecee\SimpleRouter\SimpleRouter;
  19. class AccountController implements IRouteController
  20. {
  21. public static function getToken(): string
  22. {
  23. $username = input("username");
  24. $password = password_hash(input("password"), PASSWORD_DEFAULT);
  25. $account = new Account(
  26. username: $username,
  27. password: $password,
  28. picture_hash: "default",
  29. verified: false
  30. );
  31. if ($account->Exists()) { // Account already exists
  32. $account->Load();
  33. if (password_verify($password, $account->password)) throw new UnauthenticatedException($account->id, 401);
  34. $session = new Session(account_id: $account->id);
  35. } else { // Create a new account
  36. $session = new Session(account_id: $account->Save());
  37. }
  38. CORSHelper();
  39. $token = $session->Save();
  40. $session->Load();
  41. return api_json([
  42. "token" => $token,
  43. "auth_date" => $session->date_authenticated
  44. ]);
  45. }
  46. public static function getAccount($id): string
  47. {
  48. if (!signed_in(request())) {
  49. $usernames = explode(",", Hajeebtok::$Config->GetByDotKey("Service.FakeUsernames"));
  50. CORSHelper();
  51. return api_json([
  52. "id" => $id,
  53. "username" => $usernames[rand(0, count($usernames) - 1)],
  54. "verified" => false,
  55. "bio" => "SIGN IN to see this EPIC content!!!",
  56. "pictureHash" => null,
  57. "followers" => rand(5, 38203),
  58. "following" => rand(5, 6243),
  59. "myself" => false,
  60. "links" => []
  61. ]);
  62. }
  63. if ($id === "myself") $id = get_token_id(request());
  64. Logger::Debug($id);
  65. Logger::Debug("Getting account id ($id).");
  66. $account = new Account(id: $id);
  67. $account->Load();
  68. $followers = count(new Follow(followee_id: $id)->LoadMany());
  69. $following = count(new Follow(follower_id: $id)->LoadMany());
  70. try {
  71. $links = new Link(account_id: $id)->LoadMany();
  72. } catch (Exception $e) {
  73. $links = [];
  74. }
  75. CORSHelper();
  76. return api_json([
  77. "id" => $id,
  78. "username" => $account->username,
  79. "verified" => $account->verified,
  80. "bio" => $account->bio,
  81. "pictureHash" => $account->picture_hash,
  82. "followers" => $followers,
  83. "following" => $following,
  84. "myself" => $id == get_token_id(request()),
  85. "links" => $links
  86. ]);
  87. }
  88. public static function search(): string
  89. {
  90. $query = input("query");
  91. $account = new Account(username: $query);
  92. $accounts = $account->LoadMany();
  93. return api_json($accounts);
  94. }
  95. public static function getVideos($id): string
  96. {
  97. if(!signed_in(request())) {
  98. $titles = explode(",", Hajeebtok::$Config->GetByDotKey("Service.FakeTitles"));
  99. $descriptions = explode(",", Hajeebtok::$Config->GetByDotKey("Service.FakeDescriptions"));
  100. $usernames = explode(",", Hajeebtok::$Config->GetByDotKey("Service.FakeUsernames"));
  101. $feed = [];
  102. for($i = 0; $i < rand(6, 20); $i++) {
  103. $feed[] = [
  104. "id" => rand(1, 10),
  105. "title" => $titles[rand(0, count($titles) - 1)],
  106. "description" => $descriptions[rand(0, count($descriptions) - 1)],
  107. "likes" => rand(20000, 37020),
  108. "dislikes" => rand(2, 12343),
  109. "comments" => rand(2, 1029),
  110. "shares" => rand(2, 200000),
  111. "author" => [
  112. "id" => rand(2, 59),
  113. "pictureHash" => null,
  114. "username" => $usernames[rand(0, count($usernames) - 1)],
  115. ],
  116. ];
  117. }
  118. CORSHelper();
  119. return api_json($feed);
  120. }
  121. if ($id === "myself") $id = get_token_id(request());
  122. $account = new Account(id: $id);
  123. $video_number = intval(input("video") ?? "0");
  124. $data = Hajeebtok::$Database->Query("SELECT * FROM videos WHERE author_id = :author_id", ["author_id" => $account->id]);
  125. if (empty($data)) throw new VideoNotFoundException(0, 404);
  126. $videos = [];
  127. $valid_video = false;
  128. foreach ($data as $video) {
  129. if($video_number === 0) $valid_video = true;
  130. if($video["id"] === $video_number) $valid_video = true;
  131. if(!$valid_video) continue;
  132. $account = new Account($video["author_id"]);
  133. $account->Load();
  134. $videos[] = ["id" => $video["id"],
  135. "title" => $video["title"],
  136. "description" => $video["description"],
  137. "likes" => $video["likes"],
  138. "dislikes" => $video["dislikes"],
  139. "comments" => Hajeebtok::$Database->Single("SELECT COUNT(*) FROM comments WHERE video_id = :id", ["id" => $video["id"]]),
  140. "shares" => Hajeebtok::$Database->Single("SELECT COUNT(*) FROM messages INNER JOIN videos ON messages.video_id = videos.id WHERE videos.id = :id", ["id" => $video["id"]]),
  141. "author" => [
  142. "id" => $video["author_id"],
  143. "pictureHash" => $account->picture_hash,
  144. "username" => $account->username,
  145. ],
  146. ];
  147. }
  148. CORSHelper();
  149. return api_json($videos);
  150. }
  151. public static function getPicture($id): string
  152. {
  153. $signed_in = signed_in(request());
  154. if ($id === "myself") $id = get_token_id(request());
  155. if ($signed_in) {
  156. try {
  157. $account = new Account(id: $id);
  158. $account->Load();
  159. $picture_path = APP_ROOT . "/usercontent/pictures/$account->picture_hash.png";
  160. } catch (Exception $e) {
  161. $picture_path = APP_ROOT . "/usercontent/pictures/not_found.png";
  162. }
  163. } else {
  164. // this is hardcoded because i dont care
  165. $picture_path = APP_ROOT . "/usercontent/pictures/premium_" . rand(1, 57) . ".png";
  166. }
  167. $mimeTypes = new MimeTypes();
  168. $picture_contents = file_get_contents($picture_path);
  169. $picture_size = filesize($picture_path);
  170. $mime = $mimeTypes->getMimeType(pathinfo($picture_path, PATHINFO_EXTENSION));
  171. $response = response();
  172. $response->header("Content-Type: $mime");
  173. $response->header("Content-Length: $picture_size");
  174. $response->header("Cache-Control: max-age=3600, public");
  175. return $picture_contents;
  176. }
  177. public static function getAvailablePremiumProfilePictures(): string
  178. {
  179. $pictures = [];
  180. for ($i = 1; $i <= 57; $i++) {
  181. $pictures[] = $i;
  182. }
  183. return api_json($pictures);
  184. }
  185. public static function getPremiumProfilePicture($id): string
  186. {
  187. $picture_path = APP_ROOT . "/usercontent/pictures/premium_$id.png";
  188. $mime_types = new MimeTypes();
  189. $picture_contents = file_get_contents($picture_path);
  190. $picture_size = filesize($picture_path);
  191. $mime = $mime_types->getMimeType(pathinfo($picture_path, PATHINFO_EXTENSION));
  192. $response = response();
  193. $response->header("Content-Type: $mime");
  194. $response->header("Content-Length: $picture_size");
  195. $response->header("Cache-Control: max-age=3600, public");
  196. return $picture_contents;
  197. }
  198. public static function updateAccount(): string
  199. {
  200. if (!signed_in(request())) throw new UnauthenticatedException(0, 401);
  201. $id = get_token_id(request());
  202. $picture_hash = input("picture_hash");
  203. $picture = request()->getInputHandler()->file("picture");
  204. $bio = input("bio");
  205. if (empty($picture) && !empty($picture_hash)) {
  206. $valid_picture_hash_list = [
  207. "default",
  208. "premium_1",
  209. "premium_2",
  210. "premium_3",
  211. "premium_4",
  212. "premium_5",
  213. "premium_6",
  214. "premium_7",
  215. "premium_8",
  216. "premium_9",
  217. "premium_10",
  218. "premium_11",
  219. "premium_12",
  220. "premium_13",
  221. "premium_14",
  222. "premium_15",
  223. "premium_16",
  224. "premium_17",
  225. "premium_18",
  226. "premium_19",
  227. "premium_20",
  228. "premium_21",
  229. "premium_22",
  230. "premium_23",
  231. "premium_24",
  232. "premium_25",
  233. "premium_26",
  234. "premium_27",
  235. "premium_28",
  236. "premium_29",
  237. "premium_30",
  238. "premium_31",
  239. "premium_32",
  240. "premium_33",
  241. "premium_34",
  242. "premium_35",
  243. "premium_36",
  244. "premium_37",
  245. "premium_38",
  246. "premium_39",
  247. "premium_40",
  248. "premium_41",
  249. "premium_42",
  250. "premium_43",
  251. "premium_44",
  252. "premium_45",
  253. "premium_46",
  254. "premium_47",
  255. "premium_48",
  256. "premium_49",
  257. "premium_50",
  258. "premium_51",
  259. "premium_52",
  260. "premium_53",
  261. "premium_54",
  262. "premium_55",
  263. "premium_56",
  264. "premium_57"
  265. ];
  266. if (!in_array($picture_hash, $valid_picture_hash_list)) throw new SecurityFaultException("Attempt to path trace on /update endpoint.", 400);
  267. } else if (!empty($picture) && empty($picture_hash)) {
  268. $picture_hash = hash("sha256", $picture);
  269. $picture_path = APP_ROOT . "/usercontent/pictures/$picture_hash.png";
  270. $size = getimagesize($picture);
  271. $crop = min($size[0], $size[1]);
  272. $image_contents = file_get_contents($picture);
  273. $image_string = imagecreatefromstring($image_contents);
  274. $cropped_image = imagecrop($image_string, [
  275. "x" => 0,
  276. "y" => 0,
  277. "width" => $crop,
  278. "height" => $crop
  279. ]);
  280. imagepng($cropped_image, $picture_path); // save image and crop and turn into png (i love php)
  281. } else if (!empty($picture) && !empty($picture_hash)) {
  282. throw new InvalidRequestException(400);
  283. }
  284. $old_account = new Account(id: $id);
  285. $old_account->Load();
  286. $new_account = new Account(
  287. id: $id,
  288. username: $old_account->username,
  289. password: $old_account->password,
  290. picture_hash: $picture_hash ?? $old_account->picture_hash,
  291. verified: $old_account->verified,
  292. bio: $bio ?? $old_account->bio,
  293. );
  294. CORSHelper();
  295. $new_account->Update();
  296. return api_json([
  297. "id" => $new_account->id,
  298. "username" => $new_account->username,
  299. "pictureHash" => $new_account->picture_hash,
  300. "bio" => $new_account->bio,
  301. "verified" => $new_account->verified,
  302. ]);
  303. }
  304. public static function addLink(): string
  305. {
  306. if (!signed_in(request())) throw new UnauthenticatedException(0, 401);
  307. $account_id = get_token_id(request());
  308. $link = input("link");
  309. $link_type = input("linkType");
  310. $link_enum_type = LinkEnum::tryFrom($link_type);
  311. // todo: add enum type filtering
  312. $link = new Link(account_id: $account_id, type: $link_enum_type, url: $link);
  313. $link->Save();
  314. return api_json([
  315. "id" => $link->id,
  316. "url" => $link->url,
  317. "type" => $link->type->value,
  318. "account_id" => $link->account_id
  319. ]);
  320. }
  321. public static function getFollowers($id): string
  322. {
  323. if ($id === "myself") $id = get_token_id(request());
  324. $followers = new Follow(followee_id: $id)->LoadMany();
  325. if (empty($followers)) throw new FollowNotFoundException(0, 404);
  326. for ($i = 0; $i < count($followers); $i++) {
  327. $follower = $followers[$i]["follower_id"];
  328. $account = new Account(id: $follower);
  329. $account->Load();
  330. $followers[$i] = [
  331. "followee_id" => (int)$id,
  332. "follower_id" => $follower,
  333. "username" => $account->username,
  334. "pictureHash" => $account->picture_hash,
  335. "verified" => $account->verified
  336. ];
  337. }
  338. return api_json($followers);
  339. }
  340. public static function getFollowing($id): string
  341. {
  342. if ($id === "myself") $id = get_token_id(request());
  343. $following = new Follow(follower_id: $id)->LoadMany();
  344. if (empty($following)) throw new FollowNotFoundException(0, 404);
  345. for ($i = 0; $i < count($following); $i++) {
  346. $followee = $following[$i]["followee_id"];
  347. $account = new Account(id: $followee);
  348. $account->Load();
  349. $following[$i] = [
  350. "followee_id" => $followee,
  351. "follower_id" => (int)$id,
  352. "username" => $account->username,
  353. "pictureHash" => $account->picture_hash,
  354. "verified" => $account->verified
  355. ];
  356. }
  357. return api_json($following);
  358. }
  359. public static function RegisterRoutes(): void
  360. {
  361. SimpleRouter::group([
  362. "prefix" => "/account/",
  363. ], function () {
  364. SimpleRouter::get("/availablePremiumProfilePictures", [AccountController::class, "getAvailablePremiumProfilePictures"]);
  365. SimpleRouter::get("/getPremiumProfilePicture/{id}", [AccountController::class, "getPremiumProfilePicture"]);
  366. SimpleRouter::get("/{id}/get", [AccountController::class, "getAccount"]);
  367. SimpleRouter::get("/{id}/videos", [AccountController::class, "getVideos"]);
  368. SimpleRouter::get("/{id}/picture", [AccountController::class, "getPicture"]);
  369. SimpleRouter::get("/{id}/followers", [AccountController::class, "getFollowers"]);
  370. SimpleRouter::get("/{id}/following", [AccountController::class, "getFollowing"]);
  371. SimpleRouter::post("/token", [AccountController::class, "getToken"]);
  372. SimpleRouter::post("/search", [AccountController::class, "search"]);
  373. SimpleRouter::post("/update", [AccountController::class, "updateAccount"]);
  374. SimpleRouter::post("/addLink", [AccountController::class, "addLink"]);
  375. SimpleRouter::options("/update", "CORSHelper");
  376. SimpleRouter::options("/token", "CORSHelper");
  377. SimpleRouter::options("/{id}/get", "CORSHelper");
  378. SimpleRouter::options("/{id}/videos", "CORSHelper");
  379. });
  380. }
  381. }