From 036bfe83da6290cc1ede047d54edb37872a06a04 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Mon, 1 Apr 2024 23:00:25 +0300 Subject: [PATCH 01/34] Update .gitignore --- .gitignore | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 55371e5..e722602 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,43 @@ node_modules -.vscode \ No newline at end of file +.vscode +/** + * Retrieves information about a subreddit. + * @param {string} subredditName - The name of the subreddit. + * @returns {Promise} A promise that resolves to the subreddit information. + */ +async function getSubredditInfo(subredditName) { + const url = `https://www.reddit.com/r/${subredditName}/about.json`; + try { + const response = await fetch(url); + if (response.status !== 200) { + const errorMessage = `Failed to fetch subreddit information : ${ response.statusText }`; + throw new Error(errorMessage); + } + const data = await response.json(); + return data.data; + } + catch (error) { + const errorMessage = `Error retrieving subreddit information : ${ error.message }`; + console.error(errorMessage); + throw new Error(errorMessage); + + } +} + +/** + * Reports subreddit information. + * @param {string} subredditName - The name of the subreddit. + */ +async function reportSubredditInfo(subredditName) { + try { + const subredditInfo = await getSubredditInfo(subredditName); + console.log('Subreddit Information:', subredditInfo); + } + catch (error) { + console.error('Failed to report subreddit information:', error); + } +} + +// Example usage: +reportSubredditInfo('AskReddit'); + From 19000088374a3d7d1d616ee260d6a6b02ed59c13 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Tue, 2 Apr 2024 13:28:10 +0300 Subject: [PATCH 02/34] Create subreddit info,report T4 --- subreddit info,report T4 | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 subreddit info,report T4 diff --git a/subreddit info,report T4 b/subreddit info,report T4 new file mode 100644 index 0000000..6620d04 --- /dev/null +++ b/subreddit info,report T4 @@ -0,0 +1,40 @@ +/** + * Retrieves information about a subreddit. + * @param {string} subredditName - The name of the subreddit. + * @returns {Promise} A promise that resolves to the subreddit information. + */ +async function getSubredditInfo(subredditName) { + const url = `https://www.reddit.com/r/${subredditName}/about.json`; + try { + const response = await fetch(url); + if (response.status !== 200) { + const errorMessage = `Failed to fetch subreddit information : ${ response.statusText }`; + throw new Error(errorMessage); + } + const data = await response.json(); + return data.data; + } + catch (error) { + const errorMessage = `Error retrieving subreddit information : ${ error.message }`; + console.error(errorMessage); + throw new Error(errorMessage); + + } +} + +/** + * Reports subreddit information. + * @param {string} subredditName - The name of the subreddit. + */ +async function reportSubredditInfo(subredditName) { + try { + const subredditInfo = await getSubredditInfo(subredditName); + console.log('Subreddit Information:', subredditInfo); + } + catch (error) { + console.error('Failed to report subreddit information:', error); + } +} + +// Example usage: +reportSubredditInfo('AskReddit'); From 1cae38fd2e90248e3e862fa7a02234883896b200 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Tue, 2 Apr 2024 13:28:40 +0300 Subject: [PATCH 03/34] Update .gitignore --- .gitignore | 41 ----------------------------------------- 1 file changed, 41 deletions(-) diff --git a/.gitignore b/.gitignore index e722602..76efb07 100644 --- a/.gitignore +++ b/.gitignore @@ -1,43 +1,2 @@ node_modules .vscode -/** - * Retrieves information about a subreddit. - * @param {string} subredditName - The name of the subreddit. - * @returns {Promise} A promise that resolves to the subreddit information. - */ -async function getSubredditInfo(subredditName) { - const url = `https://www.reddit.com/r/${subredditName}/about.json`; - try { - const response = await fetch(url); - if (response.status !== 200) { - const errorMessage = `Failed to fetch subreddit information : ${ response.statusText }`; - throw new Error(errorMessage); - } - const data = await response.json(); - return data.data; - } - catch (error) { - const errorMessage = `Error retrieving subreddit information : ${ error.message }`; - console.error(errorMessage); - throw new Error(errorMessage); - - } -} - -/** - * Reports subreddit information. - * @param {string} subredditName - The name of the subreddit. - */ -async function reportSubredditInfo(subredditName) { - try { - const subredditInfo = await getSubredditInfo(subredditName); - console.log('Subreddit Information:', subredditInfo); - } - catch (error) { - console.error('Failed to report subreddit information:', error); - } -} - -// Example usage: -reportSubredditInfo('AskReddit'); - From f9ac73e467bf1653bedd2afd49f65d0ab9b847e8 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Tue, 2 Apr 2024 13:38:13 +0300 Subject: [PATCH 04/34] Create subreddit info,report --- subreddit info,report | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 subreddit info,report diff --git a/subreddit info,report b/subreddit info,report new file mode 100644 index 0000000..6620d04 --- /dev/null +++ b/subreddit info,report @@ -0,0 +1,40 @@ +/** + * Retrieves information about a subreddit. + * @param {string} subredditName - The name of the subreddit. + * @returns {Promise} A promise that resolves to the subreddit information. + */ +async function getSubredditInfo(subredditName) { + const url = `https://www.reddit.com/r/${subredditName}/about.json`; + try { + const response = await fetch(url); + if (response.status !== 200) { + const errorMessage = `Failed to fetch subreddit information : ${ response.statusText }`; + throw new Error(errorMessage); + } + const data = await response.json(); + return data.data; + } + catch (error) { + const errorMessage = `Error retrieving subreddit information : ${ error.message }`; + console.error(errorMessage); + throw new Error(errorMessage); + + } +} + +/** + * Reports subreddit information. + * @param {string} subredditName - The name of the subreddit. + */ +async function reportSubredditInfo(subredditName) { + try { + const subredditInfo = await getSubredditInfo(subredditName); + console.log('Subreddit Information:', subredditInfo); + } + catch (error) { + console.error('Failed to report subreddit information:', error); + } +} + +// Example usage: +reportSubredditInfo('AskReddit'); From dfb6f733723333621e381711e0aed7a3b1327c79 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Tue, 2 Apr 2024 13:40:43 +0300 Subject: [PATCH 05/34] Update and rename subreddit info,report T4 to t --- subreddit info,report T4 | 40 ---------------------------------------- t | 1 + 2 files changed, 1 insertion(+), 40 deletions(-) delete mode 100644 subreddit info,report T4 create mode 100644 t diff --git a/subreddit info,report T4 b/subreddit info,report T4 deleted file mode 100644 index 6620d04..0000000 --- a/subreddit info,report T4 +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Retrieves information about a subreddit. - * @param {string} subredditName - The name of the subreddit. - * @returns {Promise} A promise that resolves to the subreddit information. - */ -async function getSubredditInfo(subredditName) { - const url = `https://www.reddit.com/r/${subredditName}/about.json`; - try { - const response = await fetch(url); - if (response.status !== 200) { - const errorMessage = `Failed to fetch subreddit information : ${ response.statusText }`; - throw new Error(errorMessage); - } - const data = await response.json(); - return data.data; - } - catch (error) { - const errorMessage = `Error retrieving subreddit information : ${ error.message }`; - console.error(errorMessage); - throw new Error(errorMessage); - - } -} - -/** - * Reports subreddit information. - * @param {string} subredditName - The name of the subreddit. - */ -async function reportSubredditInfo(subredditName) { - try { - const subredditInfo = await getSubredditInfo(subredditName); - console.log('Subreddit Information:', subredditInfo); - } - catch (error) { - console.error('Failed to report subreddit information:', error); - } -} - -// Example usage: -reportSubredditInfo('AskReddit'); diff --git a/t b/t new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/t @@ -0,0 +1 @@ + From 2a1367fc0357396540e53aa5cda07747ecc81d65 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Thu, 4 Apr 2024 23:56:49 +0300 Subject: [PATCH 06/34] Delete t --- t | 1 - 1 file changed, 1 deletion(-) delete mode 100644 t diff --git a/t b/t deleted file mode 100644 index 8b13789..0000000 --- a/t +++ /dev/null @@ -1 +0,0 @@ - From c04d80e7ef976d1e1b21700efdd7b175ad0de67b Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 10 Apr 2024 00:47:29 +0300 Subject: [PATCH 07/34] Create test info,report --- test info,report | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 test info,report diff --git a/test info,report b/test info,report new file mode 100644 index 0000000..513ebe2 --- /dev/null +++ b/test info,report @@ -0,0 +1,31 @@ +const { getSubredditInfo, getReportReasons } = require('./subredditFunctions'); + +describe('Subreddit Functions', () = > { + describe('getSubredditInfo', () = > { + it('should retrieve subreddit information', async() = > { + const subredditName = 'example_subreddit'; + const subredditInfo = await getSubredditInfo(subredditName); + expect(subredditInfo).toBeDefined(); + expect(subredditInfo.display_name).toBe(subredditName); + }); + + it('should handle errors gracefully', async() = > { + const invalidSubredditName = 'invalid_subreddit'; + await expect(getSubredditInfo(invalidSubredditName)).rejects.toThrow(); + }); + }); + + describe('getReportReasons', () = > { + it('should retrieve report reasons for a subreddit', async() = > { + const subredditName = 'example_subreddit'; + const reportReasons = await getReportReasons(subredditName); + expect(reportReasons).toBeDefined(); + + }); + + it('should handle errors gracefully', async() = > { + const invalidSubredditName = 'invalid_subreddit'; + await expect(getReportReasons(invalidSubredditName)).rejects.toThrow(); + }); + }); +}); From 7385511121304ad39192a3aeb4c7d5c2736e33a3 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 10 Apr 2024 00:52:02 +0300 Subject: [PATCH 08/34] Update subreddit info,report --- subreddit info,report | 47 ++++++++++++++----------------------------- 1 file changed, 15 insertions(+), 32 deletions(-) diff --git a/subreddit info,report b/subreddit info,report index 6620d04..9e04a44 100644 --- a/subreddit info,report +++ b/subreddit info,report @@ -1,40 +1,23 @@ -/** - * Retrieves information about a subreddit. - * @param {string} subredditName - The name of the subreddit. - * @returns {Promise} A promise that resolves to the subreddit information. - */ -async function getSubredditInfo(subredditName) { - const url = `https://www.reddit.com/r/${subredditName}/about.json`; - try { - const response = await fetch(url); - if (response.status !== 200) { - const errorMessage = `Failed to fetch subreddit information : ${ response.statusText }`; - throw new Error(errorMessage); - } - const data = await response.json(); - return data.data; +const Subreddit = require('../models/subredditModel'); + +exports.getSubredditInfo = async(req, res, next) = > { + try { + const subredditName = req.params.subredditName; + const subredditInfo = await Subreddit.getSubredditInfo(subredditName); + res.status(200).json(subredditInfo); } catch (error) { - const errorMessage = `Error retrieving subreddit information : ${ error.message }`; - console.error(errorMessage); - throw new Error(errorMessage); - + res.status(500).json({ error: error.message }); } -} +}; -/** - * Reports subreddit information. - * @param {string} subredditName - The name of the subreddit. - */ -async function reportSubredditInfo(subredditName) { +exports.reportSubredditInfo = async(req, res, next) = > { try { - const subredditInfo = await getSubredditInfo(subredditName); - console.log('Subreddit Information:', subredditInfo); + const subredditName = req.params.subredditName; + await Subreddit.reportSubredditInfo(subredditName); + res.status(200).json({ message: 'Subreddit information reported successfully.' }); } catch (error) { - console.error('Failed to report subreddit information:', error); + res.status(500).json({ error: error.message }); } -} - -// Example usage: -reportSubredditInfo('AskReddit'); +}; From 2c019f71f1a1ec68381ae62cd49782bd34b1ed27 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 17 Apr 2024 08:47:11 +0300 Subject: [PATCH 09/34] Update subreddit info,report --- subreddit info,report | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/subreddit info,report b/subreddit info,report index 9e04a44..96baea2 100644 --- a/subreddit info,report +++ b/subreddit info,report @@ -1,23 +1,21 @@ -const Subreddit = require('../models/subredditModel'); +const SubredditModel = require('../models/SubredditModel'); -exports.getSubredditInfo = async(req, res, next) = > { +exports.getSubredditInfo = async (req, res, next) => { try { const subredditName = req.params.subredditName; - const subredditInfo = await Subreddit.getSubredditInfo(subredditName); + const subredditInfo = await SubredditModel.getSubredditInfo(subredditName); res.status(200).json(subredditInfo); - } - catch (error) { + } catch (error) { res.status(500).json({ error: error.message }); } }; -exports.reportSubredditInfo = async(req, res, next) = > { +exports.reportSubredditInfo = async (req, res, next) => { try { const subredditName = req.params.subredditName; - await Subreddit.reportSubredditInfo(subredditName); + await SubredditModel.reportSubredditInfo(subredditName); res.status(200).json({ message: 'Subreddit information reported successfully.' }); - } - catch (error) { + } catch (error) { res.status(500).json({ error: error.message }); } }; From aadc8df830009f877f2178343484987666ad3c08 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 17 Apr 2024 08:48:10 +0300 Subject: [PATCH 10/34] Update subreddit info,report From 57ebc3e56662551cbac18a07e6294252cf33a2fb Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 17 Apr 2024 08:49:36 +0300 Subject: [PATCH 11/34] Update test info,report --- test info,report | 71 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 50 insertions(+), 21 deletions(-) diff --git a/test info,report b/test info,report index 513ebe2..03d4738 100644 --- a/test info,report +++ b/test info,report @@ -1,31 +1,60 @@ -const { getSubredditInfo, getReportReasons } = require('./subredditFunctions'); - -describe('Subreddit Functions', () = > { - describe('getSubredditInfo', () = > { - it('should retrieve subreddit information', async() = > { - const subredditName = 'example_subreddit'; - const subredditInfo = await getSubredditInfo(subredditName); - expect(subredditInfo).toBeDefined(); - expect(subredditInfo.display_name).toBe(subredditName); +const { getSubredditInfo, reportSubredditInfo } = require('./subredditController'); +const SubredditModel = require('../models/SubredditModel'); + +describe('Subreddit Controller', () => { + describe('getSubredditInfo', () => { + it('should retrieve subreddit information', async () => { + const req = { params: { subredditName: 'example_subreddit' } }; + const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; + + const subredditInfo = { name: 'example_subreddit', description: 'Sample subreddit description' }; + jest.spyOn(SubredditModel, 'getSubredditInfo').mockResolvedValue(subredditInfo); + + await getSubredditInfo(req, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledWith(subredditInfo); }); - it('should handle errors gracefully', async() = > { - const invalidSubredditName = 'invalid_subreddit'; - await expect(getSubredditInfo(invalidSubredditName)).rejects.toThrow(); + it('should handle errors gracefully', async () => { + const req = { params: { subredditName: 'invalid_subreddit' } }; + const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; + + jest.spyOn(SubredditModel, 'getSubredditInfo').mockRejectedValue(new Error('Subreddit not found')); + + await getSubredditInfo(req, res); + + expect(res.status).toHaveBeenCalledWith(500); + expect(res.json).toHaveBeenCalledWith({ error: 'Subreddit not found' }); }); }); - describe('getReportReasons', () = > { - it('should retrieve report reasons for a subreddit', async() = > { - const subredditName = 'example_subreddit'; - const reportReasons = await getReportReasons(subredditName); - expect(reportReasons).toBeDefined(); - + describe('reportSubredditInfo', () => { + it('should report subreddit information', async () => { + const req = { params: { subredditName: 'example_subreddit' } }; + const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; + + jest.spyOn(SubredditModel, 'reportSubredditInfo').mockResolvedValue(); + + await reportSubredditInfo(req, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledWith({ message: 'Subreddit information reported successfully.' }); }); - it('should handle errors gracefully', async() = > { - const invalidSubredditName = 'invalid_subreddit'; - await expect(getReportReasons(invalidSubredditName)).rejects.toThrow(); + it('should handle errors gracefully', async () => { + const req = { params: { subredditName: 'invalid_subreddit' } }; + const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; + + jest.spyOn(SubredditModel, 'reportSubredditInfo').mockRejectedValue(new Error('Subreddit not found')); + + await reportSubredditInfo(req, res); + + expect(res.status).toHaveBeenCalledWith(500); + expect(res.json).toHaveBeenCalledWith({ error: 'Subreddit not found' }); }); }); + + }); + From a7bc41cef74a506adb8a839815c3820fcf17c47b Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 24 Apr 2024 23:08:58 +0300 Subject: [PATCH 12/34] Create saved_categories,sendreplies,set_suggested_sort --- ..._categories,sendreplies,set_suggested_sort | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 saved_categories,sendreplies,set_suggested_sort diff --git a/saved_categories,sendreplies,set_suggested_sort b/saved_categories,sendreplies,set_suggested_sort new file mode 100644 index 0000000..b782d01 --- /dev/null +++ b/saved_categories,sendreplies,set_suggested_sort @@ -0,0 +1,33 @@ +const SubredditModel = require('../models/SubredditModel'); + +exports.getSavedCategories = async (req, res, next) => { + try { + const username = req.params.username; + const savedCategories = await SubredditModel.getSavedCategories(username); + res.status(200).json(savedCategories); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; + +exports.setSendReplies = async (req, res, next) => { + try { + const username = req.params.username; + const enable = req.body.enable; + await SubredditModel.setSendReplies(username, enable); + res.status(200).json({ message: 'Send replies status set successfully.' }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; + +exports.setSuggestedSort = async (req, res, next) => { + try { + const subredditName = req.params.subredditName; + const suggestedSort = req.body.suggestedSort; + await SubredditModel.setSuggestedSort(subredditName, suggestedSort); + res.status(200).json({ message: 'Suggested sort set successfully.' }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; From a8392d78430e398cbf066d2c3c05cb6e54c2e3d6 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 24 Apr 2024 23:10:22 +0300 Subject: [PATCH 13/34] Create test saved_categories,sendreplies,set_suggested_sort --- ..._categories,sendreplies,set_suggested_sort | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 test saved_categories,sendreplies,set_suggested_sort diff --git a/test saved_categories,sendreplies,set_suggested_sort b/test saved_categories,sendreplies,set_suggested_sort new file mode 100644 index 0000000..5d07b6e --- /dev/null +++ b/test saved_categories,sendreplies,set_suggested_sort @@ -0,0 +1,83 @@ +const { getSavedCategories, setSendReplies, setSuggestedSort } = require('./savedCategoriesController'); +const UserModel = require('../models/UserModel'); + +describe('Saved Categories Controller', () => { + describe('getSavedCategories', () => { + it('should retrieve saved categories for a user', async () => { + const req = { params: { username: 'example_user' } }; + const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; + + const savedCategories = ['category1', 'category2']; + jest.spyOn(UserModel, 'getSavedCategories').mockResolvedValue(savedCategories); + + await getSavedCategories(req, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledWith(savedCategories); + }); + + it('should handle errors gracefully', async () => { + const req = { params: { username: 'invalid_user' } }; + const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; + + jest.spyOn(UserModel, 'getSavedCategories').mockRejectedValue(new Error('User not found')); + + await getSavedCategories(req, res); + + expect(res.status).toHaveBeenCalledWith(500); + expect(res.json).toHaveBeenCalledWith({ error: 'User not found' }); + }); + }); + + describe('setSendReplies', () => { + it('should set send replies status for a user', async () => { + const req = { params: { username: 'example_user' }, body: { enable: true } }; + const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; + + jest.spyOn(UserModel, 'setSendReplies').mockResolvedValue(); + + await setSendReplies(req, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledWith({ message: 'Send replies status set successfully.' }); + }); + + it('should handle errors gracefully', async () => { + const req = { params: { username: 'invalid_user' }, body: { enable: true } }; + const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; + + jest.spyOn(UserModel, 'setSendReplies').mockRejectedValue(new Error('User not found')); + + await setSendReplies(req, res); + + expect(res.status).toHaveBeenCalledWith(500); + expect(res.json).toHaveBeenCalledWith({ error: 'User not found' }); + }); + }); + + describe('setSuggestedSort', () => { + it('should set suggested sort for a subreddit', async () => { + const req = { params: { subredditName: 'example_subreddit' }, body: { suggestedSort: 'new' } }; + const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; + + jest.spyOn(UserModel, 'setSuggestedSort').mockResolvedValue(); + + await setSuggestedSort(req, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledWith({ message: 'Suggested sort set successfully.' }); + }); + + it('should handle errors gracefully', async () => { + const req = { params: { subredditName: 'invalid_subreddit' }, body: { suggestedSort: 'new' } }; + const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; + + jest.spyOn(UserModel, 'setSuggestedSort').mockRejectedValue(new Error('Subreddit not found')); + + await setSuggestedSort(req, res); + + expect(res.status).toHaveBeenCalledWith(500); + expect(res.json).toHaveBeenCalledWith({ error: 'Subreddit not found' }); + }); + }); +}); From 5dc38526cda88d2af6341331657febf497c4f81b Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 24 Apr 2024 23:14:14 +0300 Subject: [PATCH 14/34] Create delete_sr_banner,delete_sr_icon,upload_sr_icon --- ...te_sr_banner,delete_sr_icon,upload_sr_icon | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 delete_sr_banner,delete_sr_icon,upload_sr_icon diff --git a/delete_sr_banner,delete_sr_icon,upload_sr_icon b/delete_sr_banner,delete_sr_icon,upload_sr_icon new file mode 100644 index 0000000..c8beeac --- /dev/null +++ b/delete_sr_banner,delete_sr_icon,upload_sr_icon @@ -0,0 +1,32 @@ +const SubredditModel = require('../models/SubredditModel'); + +exports.deleteSrBanner = async (req, res, next) => { + try { + const subredditName = req.params.subredditName; + await SubredditModel.deleteBanner(subredditName); + res.status(200).json({ message: 'Subreddit banner deleted successfully.' }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; + +exports.deleteSrIcon = async (req, res, next) => { + try { + const subredditName = req.params.subredditName; + await SubredditModel.deleteIcon(subredditName); + res.status(200).json({ message: 'Subreddit icon deleted successfully.' }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; + +exports.uploadSrIcon = async (req, res, next) => { + try { + const subredditName = req.params.subredditName; + const { iconFile } = req.body; + await SubredditModel.uploadIcon(subredditName, iconFile); + res.status(200).json({ message: 'Subreddit icon uploaded successfully.' }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; From 7e882fab8e7f3aa47b0b4a88ed9f14a0081291cb Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 24 Apr 2024 23:16:48 +0300 Subject: [PATCH 15/34] Create test delete_sr_banner,delete_sr_icon,upload_sr_icon --- ...te_sr_banner,delete_sr_icon,upload_sr_icon | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 test delete_sr_banner,delete_sr_icon,upload_sr_icon diff --git a/test delete_sr_banner,delete_sr_icon,upload_sr_icon b/test delete_sr_banner,delete_sr_icon,upload_sr_icon new file mode 100644 index 0000000..d4a484d --- /dev/null +++ b/test delete_sr_banner,delete_sr_icon,upload_sr_icon @@ -0,0 +1,44 @@ +const { deleteSrBanner, deleteSrIcon, uploadSrIcon } = require('./subredditFunctions'); + +describe('Subreddit Functions', () => { + describe('deleteSrBanner', () => { + it('should delete the subreddit banner', async () => { + const subredditName = 'example_subreddit'; + const result = await deleteSrBanner(subredditName); + expect(result).toEqual({ message: 'Subreddit banner deleted successfully.' }); + }); + + it('should handle errors gracefully', async () => { + const invalidSubredditName = 'invalid_subreddit'; + await expect(deleteSrBanner(invalidSubredditName)).rejects.toThrow(); + }); + }); + + describe('deleteSrIcon', () => { + it('should delete the subreddit icon', async () => { + const subredditName = 'example_subreddit'; + const result = await deleteSrIcon(subredditName); + expect(result).toEqual({ message: 'Subreddit icon deleted successfully.' }); + }); + + it('should handle errors gracefully', async () => { + const invalidSubredditName = 'invalid_subreddit'; + await expect(deleteSrIcon(invalidSubredditName)).rejects.toThrow(); + }); + }); + + describe('uploadSrIcon', () => { + it('should upload the subreddit icon', async () => { + const subredditName = 'example_subreddit'; + const iconData = 'example_icon_data'; + const result = await uploadSrIcon(subredditName, iconData); + expect(result).toEqual({ message: 'Subreddit icon uploaded successfully.' }); + }); + + it('should handle errors gracefully', async () => { + const invalidSubredditName = 'invalid_subreddit'; + const iconData = 'example_icon_data'; + await expect(uploadSrIcon(invalidSubredditName, iconData)).rejects.toThrow(); + }); + }); +}); From 2f1bc437fafb7529a748b380640c0990dafcd7a7 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 24 Apr 2024 23:21:52 +0300 Subject: [PATCH 16/34] Create approve,remove,show_comment,leavemoderator,accept_moderator_invite --- ...ent,leavemoderator,accept_moderator_invite | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 approve,remove,show_comment,leavemoderator,accept_moderator_invite diff --git a/approve,remove,show_comment,leavemoderator,accept_moderator_invite b/approve,remove,show_comment,leavemoderator,accept_moderator_invite new file mode 100644 index 0000000..abaa942 --- /dev/null +++ b/approve,remove,show_comment,leavemoderator,accept_moderator_invite @@ -0,0 +1,51 @@ +const CommentModel = require('../models/CommentModel'); + +exports.approve = async (req, res, next) => { + try { + const { id } = req.params; + await CommentModel.approve(id); + res.status(200).json({ message: 'Item approved successfully.' }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; + +exports.remove = async (req, res, next) => { + try { + const { id } = req.params; + await CommentModel.remove(id); + res.status(200).json({ message: 'Item removed successfully.' }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; + +exports.showComment = async (req, res, next) => { + try { + const { commentId } = req.params; + await CommentModel.show(commentId); + res.status(200).json({ message: 'Comment shown successfully.' }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; + +exports.leaveModerator = async (req, res, next) => { + try { + const { subredditName } = req.params; + await CommentModel.leaveModerator(subredditName); + res.status(200).json({ message: 'Left moderatorship successfully.' }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; + +exports.acceptModeratorInvite = async (req, res, next) => { + try { + const { subredditName } = req.params; + await CommentModel.acceptModeratorInvite(subredditName); + res.status(200).json({ message: 'Moderator invitation accepted successfully.' }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; From dba0a8b96496b00f48606d8472380b8bdb57de90 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 24 Apr 2024 23:24:35 +0300 Subject: [PATCH 17/34] Create test approve,remove,show_comment,leavemoderator,accept_moderator_invite --- ...ent,leavemoderator,accept_moderator_invite | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 test approve,remove,show_comment,leavemoderator,accept_moderator_invite diff --git a/test approve,remove,show_comment,leavemoderator,accept_moderator_invite b/test approve,remove,show_comment,leavemoderator,accept_moderator_invite new file mode 100644 index 0000000..2b6dd5c --- /dev/null +++ b/test approve,remove,show_comment,leavemoderator,accept_moderator_invite @@ -0,0 +1,74 @@ +const { + approve, + remove, + show_comment, + leave_moderator, + accept_moderator_invite +} = require('./subredditFunctions'); + +describe('Subreddit Functions', () => { + describe('approve', () => { + it('should approve a comment or submission', async () => { + const id = 'example_id'; + const result = await approve(id); + expect(result).toEqual({ message: 'Item approved successfully.' }); + }); + + it('should handle errors gracefully', async () => { + const invalidId = 'invalid_id'; + await expect(approve(invalidId)).rejects.toThrow(); + }); + }); + + describe('remove', () => { + it('should remove a comment or submission', async () => { + const id = 'example_id'; + const result = await remove(id); + expect(result).toEqual({ message: 'Item removed successfully.' }); + }); + + it('should handle errors gracefully', async () => { + const invalidId = 'invalid_id'; + await expect(remove(invalidId)).rejects.toThrow(); + }); + }); + + describe('show_comment', () => { + it('should show a comment', async () => { + const commentId = 'example_comment_id'; + const result = await show_comment(commentId); + expect(result).toEqual({ message: 'Comment shown successfully.' }); + }); + + it('should handle errors gracefully', async () => { + const invalidCommentId = 'invalid_comment_id'; + await expect(show_comment(invalidCommentId)).rejects.toThrow(); + }); + }); + + describe('leave_moderator', () => { + it('should leave moderatorship of a subreddit', async () => { + const subredditName = 'example_subreddit'; + const result = await leave_moderator(subredditName); + expect(result).toEqual({ message: 'Moderatorship left successfully.' }); + }); + + it('should handle errors gracefully', async () => { + const invalidSubredditName = 'invalid_subreddit'; + await expect(leave_moderator(invalidSubredditName)).rejects.toThrow(); + }); + }); + + describe('accept_moderator_invite', () => { + it('should accept a moderator invitation', async () => { + const subredditName = 'example_subreddit'; + const result = await accept_moderator_invite(subredditName); + expect(result).toEqual({ message: 'Moderator invitation accepted successfully.' }); + }); + + it('should handle errors gracefully', async () => { + const invalidSubredditName = 'invalid_subreddit'; + await expect(accept_moderator_invite(invalidSubredditName)).rejects.toThrow(); + }); + }); +}); From 10546155c4086b6e93ef1f8b0b3fdf60d9c4b448 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 24 Apr 2024 23:29:26 +0300 Subject: [PATCH 18/34] Create site_admin;about;edite --- site_admin;about;edite | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 site_admin;about;edite diff --git a/site_admin;about;edite b/site_admin;about;edite new file mode 100644 index 0000000..63df42a --- /dev/null +++ b/site_admin;about;edite @@ -0,0 +1,20 @@ +const AdminModel = require('../models/AdminModel'); + +exports.siteAdmin = async (req, res, next) => { + try { + const adminInfo = await AdminModel.getAdminInfo(); + res.status(200).json(adminInfo); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; + +exports.editAbout = async (req, res, next) => { + try { + const { subredditName, aboutText } = req.body; + await AdminModel.editAbout(subredditName, aboutText); + res.status(200).json({ message: 'Subreddit about section edited successfully.' }); + } catch (error) { + res.status(500).json({ error: error.message }); + } +}; From f721464ad2eefffc8a63740cb04fac1878a19cde Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Wed, 24 Apr 2024 23:31:30 +0300 Subject: [PATCH 19/34] Create test site_admin;about;edite --- test site_admin;about;edite | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 test site_admin;about;edite diff --git a/test site_admin;about;edite b/test site_admin;about;edite new file mode 100644 index 0000000..cf2a0e0 --- /dev/null +++ b/test site_admin;about;edite @@ -0,0 +1,35 @@ +const { + site_admin, + edit_about +} = require('./subredditFunctions'); + +describe('Subreddit Functions', () => { + describe('site_admin', () => { + it('should retrieve site admin information', async () => { + const adminInfo = await site_admin(); + expect(adminInfo).toBeDefined(); + + }); + + it('should handle errors gracefully', async () => { + await expect(site_admin()).rejects.toThrow(); + + }); + }); + + describe('edit_about', () => { + it('should edit the about section of a subreddit', async () => { + const subredditName = 'example_subreddit'; + const aboutText = 'New about text for the subreddit.'; + const result = await edit_about(subredditName, aboutText); + expect(result).toEqual({ message: 'About section edited successfully.' }); + }); + + it('should handle errors gracefully', async () => { + const subredditName = 'invalid_subreddit'; + const aboutText = 'New about text for the subreddit.'; + await expect(edit_about(subredditName, aboutText)).rejects.toThrow(); + + }); + }); +}); From 7bef2cbb40a69e79f3666f25beffa0bba9dd2034 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 01:32:12 +0300 Subject: [PATCH 20/34] Update subreddit info,report --- subreddit info,report | 77 +++++++++++++++++++++++++++++++++---------- 1 file changed, 60 insertions(+), 17 deletions(-) diff --git a/subreddit info,report b/subreddit info,report index 96baea2..1275e29 100644 --- a/subreddit info,report +++ b/subreddit info,report @@ -1,21 +1,64 @@ -const SubredditModel = require('../models/SubredditModel'); +const express = require('express'); +const mongoose = require('mongoose'); +const bodyParser = require('body-parser'); +const jwt = require('jsonwebtoken'); +const Subreddit = require('./models/subreddit'); -exports.getSubredditInfo = async (req, res, next) => { - try { - const subredditName = req.params.subredditName; - const subredditInfo = await SubredditModel.getSubredditInfo(subredditName); - res.status(200).json(subredditInfo); - } catch (error) { - res.status(500).json({ error: error.message }); +const app = express(); +app.use(bodyParser.json()); + +// Connect to MongoDB +mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true }) + .then(() => console.log('MongoDB connected')) + .catch(err => console.error('MongoDB connection error:', err)); + +async function authenticateUser(req, res, next) { + try { + const token = req.headers.authorization ? req.headers.authorization.split(' ')[1] : req.cookies.jwt; + if (!token) { + return res.status(401).json({ error: 'Unauthorized: No token provided' }); + } + const decoded = jwt.verify(token, process.env.JWT_SECRET); + const user = await userModel.findById(decoded.userID); + if (!user) { + return res.status(401).json({ error: 'Unauthorized: User not found' }); } -}; + req.user = user; + next(); + } catch (error) { + console.error('Authentication error:', error); + return res.status(401).json({ error: 'Unauthorized: Invalid token' }); + } +} +// Task:subreddit_info +app.get('/subreddit_info/:id', authenticateUser, async (req, res) => { + try { + const subredditId = req.params.id; + const subreddit = await Subreddit.findById(subredditId); + if (!subreddit) { + return res.status(404).json({ error: 'Subreddit not found' }); + } + return res.status(200).json(subreddit); + } catch (error) { + console.error('Error fetching subreddit information:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); -exports.reportSubredditInfo = async (req, res, next) => { - try { - const subredditName = req.params.subredditName; - await SubredditModel.reportSubredditInfo(subredditName); - res.status(200).json({ message: 'Subreddit information reported successfully.' }); - } catch (error) { - res.status(500).json({ error: error.message }); +// Task:report +app.post('/report', authenticateUser, async (req, res) => { + try { + const { postId, reason } = req.body; + if (!postId || !reason) { + return res.status(400).json({ error: 'Post ID and reason are required' }); } -}; + + return res.status(200).json({ message: 'Post reported successfully' }); + } catch (error) { + console.error('Error reporting post:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + +// Export the app for testing +module.exports = app; From e2083a831b20fed07907714886760c00f01392b4 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 01:34:16 +0300 Subject: [PATCH 21/34] Update test info,report --- test info,report | 117 ++++++++++++++++++++++++----------------------- 1 file changed, 60 insertions(+), 57 deletions(-) diff --git a/test info,report b/test info,report index 03d4738..10bfe05 100644 --- a/test info,report +++ b/test info,report @@ -1,60 +1,63 @@ -const { getSubredditInfo, reportSubredditInfo } = require('./subredditController'); -const SubredditModel = require('../models/SubredditModel'); - -describe('Subreddit Controller', () => { - describe('getSubredditInfo', () => { - it('should retrieve subreddit information', async () => { - const req = { params: { subredditName: 'example_subreddit' } }; - const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; - - const subredditInfo = { name: 'example_subreddit', description: 'Sample subreddit description' }; - jest.spyOn(SubredditModel, 'getSubredditInfo').mockResolvedValue(subredditInfo); - - await getSubredditInfo(req, res); - - expect(res.status).toHaveBeenCalledWith(200); - expect(res.json).toHaveBeenCalledWith(subredditInfo); - }); - - it('should handle errors gracefully', async () => { - const req = { params: { subredditName: 'invalid_subreddit' } }; - const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; - - jest.spyOn(SubredditModel, 'getSubredditInfo').mockRejectedValue(new Error('Subreddit not found')); - - await getSubredditInfo(req, res); - - expect(res.status).toHaveBeenCalledWith(500); - expect(res.json).toHaveBeenCalledWith({ error: 'Subreddit not found' }); - }); - }); - - describe('reportSubredditInfo', () => { - it('should report subreddit information', async () => { - const req = { params: { subredditName: 'example_subreddit' } }; - const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; - - jest.spyOn(SubredditModel, 'reportSubredditInfo').mockResolvedValue(); - - await reportSubredditInfo(req, res); - - expect(res.status).toHaveBeenCalledWith(200); - expect(res.json).toHaveBeenCalledWith({ message: 'Subreddit information reported successfully.' }); - }); - - it('should handle errors gracefully', async () => { - const req = { params: { subredditName: 'invalid_subreddit' } }; - const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; - - jest.spyOn(SubredditModel, 'reportSubredditInfo').mockRejectedValue(new Error('Subreddit not found')); - - await reportSubredditInfo(req, res); - - expect(res.status).toHaveBeenCalledWith(500); - expect(res.json).toHaveBeenCalledWith({ error: 'Subreddit not found' }); - }); - }); +const request = require('supertest'); +const app = require('./app'); +const Subreddit = require('./models/subreddit'); + +describe('GET /subreddit_info/:id', () => { + it('should return subreddit information', async () => { + // Create a test subreddit + const subreddit = new Subreddit({ name: 'test_subreddit', description: 'Test description' }); + await subreddit.save(); + + // Make a GET request to retrieve subreddit information + const response = await request(app).get(`/subreddit_info/${subreddit._id}`); + + // Expect response status to be 200 and check the subreddit data + expect(response.status).toBe(200); + expect(response.body.name).toBe('test_subreddit'); + expect(response.body.description).toBe('Test description'); + }); + + it('should return 404 if subreddit ID does not exist', async () => { + // Make a GET request with a non-existing subreddit ID + const response = await request(app).get('/subreddit_info/123456789012345678901234'); + + // Expect response status to be 404 + expect(response.status).toBe(404); + }); +}); - +describe('POST /report', () => { + it('should report a post', async () => { + // Assuming postId is a valid post ID + const postId = '123456789012345678901234'; + const reason = 'Inappropriate content'; + + // Make a POST request to report a post + const response = await request(app) + .post('/report') + .send({ postId, reason }); + + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Post reported successfully'); + }); + + it('should return 400 if postId or reason is missing', async () => { + // Make a POST request with missing postId + const response1 = await request(app) + .post('/report') + .send({ reason: 'Inappropriate content' }); + + // Expect response status to be 400 + expect(response1.status).toBe(400); + + // Make a POST request with missing reason + const response2 = await request(app) + .post('/report') + .send({ postId: '123456789012345678901234' }); + + // Expect response status to be 400 + expect(response2.status).toBe(400); + }); }); From 56676b7209f88c01e5c0938382779c15b721bd5e Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 01:36:01 +0300 Subject: [PATCH 22/34] Update test info,report From ebd44b58f24bb8578364847638d6fa660eb2eb1e Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 01:39:52 +0300 Subject: [PATCH 23/34] Update saved_categories,sendreplies,set_suggested_sort --- ..._categories,sendreplies,set_suggested_sort | 133 ++++++++++++++---- 1 file changed, 108 insertions(+), 25 deletions(-) diff --git a/saved_categories,sendreplies,set_suggested_sort b/saved_categories,sendreplies,set_suggested_sort index b782d01..51568b7 100644 --- a/saved_categories,sendreplies,set_suggested_sort +++ b/saved_categories,sendreplies,set_suggested_sort @@ -1,33 +1,116 @@ -const SubredditModel = require('../models/SubredditModel'); +const express = require('express'); +const mongoose = require('mongoose'); +const bodyParser = require('body-parser'); +const jwt = require('jsonwebtoken'); +const Subreddit = require('./models/subreddit'); -exports.getSavedCategories = async (req, res, next) => { +const app = express(); +app.use(bodyParser.json()); + +// Connect to MongoDB +mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true }) + .then(() => console.log('MongoDB connected')) + .catch(err => console.error('MongoDB connection error:', err)); + + + async function authenticateUser(req, res, next) { try { - const username = req.params.username; - const savedCategories = await SubredditModel.getSavedCategories(username); - res.status(200).json(savedCategories); + + const token = req.headers.authorization ? req.headers.authorization.split(' ')[1] : req.cookies.jwt; + + if (!token) { + return res.status(401).json({ error: 'Unauthorized: No token provided' }); + } + + const decoded = jwt.verify(token, process.env.JWT_SECRET); + const user = await userModel.findById(decoded.userID); + + if (!user) { + return res.status(401).json({ error: 'Unauthorized: User not found' }); + } + + req.user = user; + next(); } catch (error) { - res.status(500).json({ error: error.message }); + console.error('Authentication error:', error); + return res.status(401).json({ error: 'Unauthorized: Invalid token' }); } -}; + } +// Task: saved_categories +app.post('/saved_categories', authenticateUser, async (req, res) => { + try { + const { subredditId, categories } = req.body; + // Check if the request body contains required fields + if (!subredditId || !categories) { + return res.status(400).json({ error: 'Subreddit ID and categories are required' }); + } + // Find the subreddit by ID + const subreddit = await Subreddit.findById(subredditId); + if (!subreddit) { + return res.status(404).json({ error: 'Subreddit not found' }); + } + // Update the subreddit's saved categories + subreddit.savedCategories = categories; + await subreddit.save(); + return res.status(200).json({ message: 'Saved categories updated successfully' }); + } catch (error) { + console.error('Error saving categories:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); -exports.setSendReplies = async (req, res, next) => { - try { - const username = req.params.username; - const enable = req.body.enable; - await SubredditModel.setSendReplies(username, enable); - res.status(200).json({ message: 'Send replies status set successfully.' }); - } catch (error) { - res.status(500).json({ error: error.message }); +// Task: sendreplies +app.post('/sendreplies', authenticateUser, async (req, res) => { + try { + const { postId, reply } = req.body; + // Check if the request body contains required fields + if (!postId || !reply) { + return res.status(400).json({ error: 'Post ID and reply content are required' }); + } + // Find the post by ID + const post = await Post.findById(postId); + if (!post) { + return res.status(404).json({ error: 'Post not found' }); } -}; + // Create a new reply document + const newReply = new Reply({ + user: req.user._id, + post: postId, + content: reply, + }); + // Save the new reply + await newReply.save(); + // Add the reply to the post's replies array + post.replies.push(newReply._id); + await post.save(); + // Return success message + return res.status(200).json({ message: 'Reply sent successfully' }); + } catch (error) { + console.error('Error sending reply:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); -exports.setSuggestedSort = async (req, res, next) => { - try { - const subredditName = req.params.subredditName; - const suggestedSort = req.body.suggestedSort; - await SubredditModel.setSuggestedSort(subredditName, suggestedSort); - res.status(200).json({ message: 'Suggested sort set successfully.' }); - } catch (error) { - res.status(500).json({ error: error.message }); + +// Task: set_suggested_sort +app.put('/set_suggested_sort', authenticateUser, async (req, res) => { + try { + const { subredditId, suggestedSort } = req.body; + // Check if the request body contains required fields + if (!subredditId || !suggestedSort) { + return res.status(400).json({ error: 'Subreddit ID and suggested sort are required' }); + } + // Find the subreddit by ID + const subreddit = await Subreddit.findById(subredditId); + if (!subreddit) { + return res.status(404).json({ error: 'Subreddit not found' }); } -}; + // Update the subreddit's suggested sort + subreddit.suggestedSort = suggestedSort; + await subreddit.save(); + return res.status(200).json({ message: 'Suggested sort updated successfully' }); + } catch (error) { + console.error('Error setting suggested sort:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); From a4373e48fb45530b5da6ee46ad921f98b455e552 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 01:42:53 +0300 Subject: [PATCH 24/34] Update test saved_categories,sendreplies,set_suggested_sort --- ..._categories,sendreplies,set_suggested_sort | 146 ++++++++---------- 1 file changed, 66 insertions(+), 80 deletions(-) diff --git a/test saved_categories,sendreplies,set_suggested_sort b/test saved_categories,sendreplies,set_suggested_sort index 5d07b6e..d16c153 100644 --- a/test saved_categories,sendreplies,set_suggested_sort +++ b/test saved_categories,sendreplies,set_suggested_sort @@ -1,83 +1,69 @@ -const { getSavedCategories, setSendReplies, setSuggestedSort } = require('./savedCategoriesController'); -const UserModel = require('../models/UserModel'); - -describe('Saved Categories Controller', () => { - describe('getSavedCategories', () => { - it('should retrieve saved categories for a user', async () => { - const req = { params: { username: 'example_user' } }; - const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; - - const savedCategories = ['category1', 'category2']; - jest.spyOn(UserModel, 'getSavedCategories').mockResolvedValue(savedCategories); - - await getSavedCategories(req, res); - - expect(res.status).toHaveBeenCalledWith(200); - expect(res.json).toHaveBeenCalledWith(savedCategories); - }); - - it('should handle errors gracefully', async () => { - const req = { params: { username: 'invalid_user' } }; - const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; - - jest.spyOn(UserModel, 'getSavedCategories').mockRejectedValue(new Error('User not found')); - - await getSavedCategories(req, res); - - expect(res.status).toHaveBeenCalledWith(500); - expect(res.json).toHaveBeenCalledWith({ error: 'User not found' }); - }); - }); - - describe('setSendReplies', () => { - it('should set send replies status for a user', async () => { - const req = { params: { username: 'example_user' }, body: { enable: true } }; - const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; - - jest.spyOn(UserModel, 'setSendReplies').mockResolvedValue(); - - await setSendReplies(req, res); - - expect(res.status).toHaveBeenCalledWith(200); - expect(res.json).toHaveBeenCalledWith({ message: 'Send replies status set successfully.' }); - }); - - it('should handle errors gracefully', async () => { - const req = { params: { username: 'invalid_user' }, body: { enable: true } }; - const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; - - jest.spyOn(UserModel, 'setSendReplies').mockRejectedValue(new Error('User not found')); - - await setSendReplies(req, res); - - expect(res.status).toHaveBeenCalledWith(500); - expect(res.json).toHaveBeenCalledWith({ error: 'User not found' }); - }); - }); - - describe('setSuggestedSort', () => { - it('should set suggested sort for a subreddit', async () => { - const req = { params: { subredditName: 'example_subreddit' }, body: { suggestedSort: 'new' } }; - const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; - - jest.spyOn(UserModel, 'setSuggestedSort').mockResolvedValue(); - - await setSuggestedSort(req, res); - - expect(res.status).toHaveBeenCalledWith(200); - expect(res.json).toHaveBeenCalledWith({ message: 'Suggested sort set successfully.' }); - }); - - it('should handle errors gracefully', async () => { - const req = { params: { subredditName: 'invalid_subreddit' }, body: { suggestedSort: 'new' } }; - const res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; - - jest.spyOn(UserModel, 'setSuggestedSort').mockRejectedValue(new Error('Subreddit not found')); +const request = require('supertest'); +const app = require('./app'); +const Subreddit = require('./models/subreddit'); +const Post = require('./models/post'); +const Reply = require('./models/reply'); + +describe('POST /saved_categories', () => { + it('should save categories to a subreddit', async () => { + // Create a test subreddit + const subreddit = new Subreddit({ name: 'test_subreddit' }); + await subreddit.save(); + + // Make a POST request to save categories + const response = await request(app) + .post('/saved_categories') + .send({ subredditId: subreddit._id, categories: ['category1', 'category2'] }); + + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Saved categories updated successfully'); + + // Fetch the subreddit from the database and check if categories are updated + const updatedSubreddit = await Subreddit.findById(subreddit._id); + expect(updatedSubreddit.savedCategories).toEqual(['category1', 'category2']); + }); +}); - await setSuggestedSort(req, res); +describe('POST /sendreplies', () => { + it('should send a reply to a post', async () => { + // Create a test post + const post = new Post({ title: 'Test Post', content: 'This is a test post' }); + await post.save(); + + // Make a POST request to send a reply + const response = await request(app) + .post('/sendreplies') + .send({ postId: post._id, reply: 'This is a test reply' }); + + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Reply sent successfully'); + + // Fetch the post from the database and check if the reply is added + const updatedPost = await Post.findById(post._id).populate('replies'); + expect(updatedPost.replies.length).toBe(1); + expect(updatedPost.replies[0].content).toBe('This is a test reply'); + }); +}); - expect(res.status).toHaveBeenCalledWith(500); - expect(res.json).toHaveBeenCalledWith({ error: 'Subreddit not found' }); - }); - }); +describe('PUT /set_suggested_sort', () => { + it('should set suggested sort for a subreddit', async () => { + // Create a test subreddit + const subreddit = new Subreddit({ name: 'test_subreddit' }); + await subreddit.save(); + + // Make a PUT request to set suggested sort + const response = await request(app) + .put('/set_suggested_sort') + .send({ subredditId: subreddit._id, suggestedSort: 'new' }); + + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Suggested sort updated successfully'); + + // Fetch the subreddit from the database and check if suggested sort is updated + const updatedSubreddit = await Subreddit.findById(subreddit._id); + expect(updatedSubreddit.suggestedSort).toBe('new'); + }); }); From 7d0d6ed4150cbe55da85df99cabd992845d66c6a Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 01:49:42 +0300 Subject: [PATCH 25/34] Update delete_sr_banner,delete_sr_icon,upload_sr_icon --- ...te_sr_banner,delete_sr_icon,upload_sr_icon | 142 ++++++++++++++---- 1 file changed, 110 insertions(+), 32 deletions(-) diff --git a/delete_sr_banner,delete_sr_icon,upload_sr_icon b/delete_sr_banner,delete_sr_icon,upload_sr_icon index c8beeac..07f4413 100644 --- a/delete_sr_banner,delete_sr_icon,upload_sr_icon +++ b/delete_sr_banner,delete_sr_icon,upload_sr_icon @@ -1,32 +1,110 @@ -const SubredditModel = require('../models/SubredditModel'); - -exports.deleteSrBanner = async (req, res, next) => { - try { - const subredditName = req.params.subredditName; - await SubredditModel.deleteBanner(subredditName); - res.status(200).json({ message: 'Subreddit banner deleted successfully.' }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}; - -exports.deleteSrIcon = async (req, res, next) => { - try { - const subredditName = req.params.subredditName; - await SubredditModel.deleteIcon(subredditName); - res.status(200).json({ message: 'Subreddit icon deleted successfully.' }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}; - -exports.uploadSrIcon = async (req, res, next) => { - try { - const subredditName = req.params.subredditName; - const { iconFile } = req.body; - await SubredditModel.uploadIcon(subredditName, iconFile); - res.status(200).json({ message: 'Subreddit icon uploaded successfully.' }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}; +const express = require('express'); +const mongoose = require('mongoose'); +const bodyParser = require('body-parser'); +const jwt = require('jsonwebtoken'); +const Subreddit = require('./models/subreddit'); + +const app = express(); +app.use(bodyParser.json()); + +// Connect to MongoDB +mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true }) + .then(() => console.log('MongoDB connected')) + .catch(err => console.error('MongoDB connection error:', err)); + +async function authenticateUser(req, res, next) { + try { + + const token = req.headers.authorization ? req.headers.authorization.split(' ')[1] : req.cookies.jwt; + + if (!token) { + return res.status(401).json({ error: 'Unauthorized: No token provided' }); + } + + const decoded = jwt.verify(token, process.env.JWT_SECRET); + + const user = await userModel.findById(decoded.userID); + + if (!user) { + return res.status(401).json({ error: 'Unauthorized: User not found' }); + } + + req.user = user; + + next(); + } catch (error) { + console.error('Authentication error:', error); + return res.status(401).json({ error: 'Unauthorized: Invalid token' }); + } +} + +// Task: delete_sr_banner +app.delete('/delete_sr_banner', authenticateUser, async (req, res) => { + try { + const { subredditId } = req.body; + // Check if the request body contains required fields + if (!subredditId) { + return res.status(400).json({ error: 'Subreddit ID is required' }); + } + // Find the subreddit by ID + const subreddit = await Subreddit.findById(subredditId); + if (!subreddit) { + return res.status(404).json({ error: 'Subreddit not found' }); + } + // Delete the subreddit's banner + subreddit.banner = null; + await subreddit.save(); + return res.status(200).json({ message: 'Subreddit banner deleted successfully' }); + } catch (error) { + console.error('Error deleting subreddit banner:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + +// Task: delete_sr_icon +app.delete('/delete_sr_icon', authenticateUser, async (req, res) => { + try { + const { subredditId } = req.body; + // Check if the request body contains required fields + if (!subredditId) { + return res.status(400).json({ error: 'Subreddit ID is required' }); + } + // Find the subreddit by ID + const subreddit = await Subreddit.findById(subredditId); + if (!subreddit) { + return res.status(404).json({ error: 'Subreddit not found' }); + } + // Delete the subreddit's icon + subreddit.icon = null; + await subreddit.save(); + return res.status(200).json({ message: 'Subreddit icon deleted successfully' }); + } catch (error) { + console.error('Error deleting subreddit icon:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + +// Task: upload_sr_icon +app.post('/upload_sr_icon', authenticateUser, async (req, res) => { + try { + const { subredditId, icon } = req.body; + // Check if the request body contains required fields + if (!subredditId || !icon) { + return res.status(400).json({ error: 'Subreddit ID and icon data are required' }); + } + // Find the subreddit by ID + const subreddit = await Subreddit.findById(subredditId); + if (!subreddit) { + return res.status(404).json({ error: 'Subreddit not found' }); + } + // Update the subreddit's icon + subreddit.icon = icon; + await subreddit.save(); + return res.status(200).json({ message: 'Subreddit icon uploaded successfully' }); + } catch (error) { + console.error('Error uploading subreddit icon:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + +module.exports = app; From 875e6c746531fb787e7595a22a9a66111d846f70 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 01:53:08 +0300 Subject: [PATCH 26/34] Update test delete_sr_banner,delete_sr_icon,upload_sr_icon --- ...te_sr_banner,delete_sr_icon,upload_sr_icon | 112 +++++++++++------- 1 file changed, 69 insertions(+), 43 deletions(-) diff --git a/test delete_sr_banner,delete_sr_icon,upload_sr_icon b/test delete_sr_banner,delete_sr_icon,upload_sr_icon index d4a484d..827b6d9 100644 --- a/test delete_sr_banner,delete_sr_icon,upload_sr_icon +++ b/test delete_sr_banner,delete_sr_icon,upload_sr_icon @@ -1,44 +1,70 @@ -const { deleteSrBanner, deleteSrIcon, uploadSrIcon } = require('./subredditFunctions'); - -describe('Subreddit Functions', () => { - describe('deleteSrBanner', () => { - it('should delete the subreddit banner', async () => { - const subredditName = 'example_subreddit'; - const result = await deleteSrBanner(subredditName); - expect(result).toEqual({ message: 'Subreddit banner deleted successfully.' }); - }); - - it('should handle errors gracefully', async () => { - const invalidSubredditName = 'invalid_subreddit'; - await expect(deleteSrBanner(invalidSubredditName)).rejects.toThrow(); - }); - }); - - describe('deleteSrIcon', () => { - it('should delete the subreddit icon', async () => { - const subredditName = 'example_subreddit'; - const result = await deleteSrIcon(subredditName); - expect(result).toEqual({ message: 'Subreddit icon deleted successfully.' }); - }); - - it('should handle errors gracefully', async () => { - const invalidSubredditName = 'invalid_subreddit'; - await expect(deleteSrIcon(invalidSubredditName)).rejects.toThrow(); - }); - }); - - describe('uploadSrIcon', () => { - it('should upload the subreddit icon', async () => { - const subredditName = 'example_subreddit'; - const iconData = 'example_icon_data'; - const result = await uploadSrIcon(subredditName, iconData); - expect(result).toEqual({ message: 'Subreddit icon uploaded successfully.' }); - }); - - it('should handle errors gracefully', async () => { - const invalidSubredditName = 'invalid_subreddit'; - const iconData = 'example_icon_data'; - await expect(uploadSrIcon(invalidSubredditName, iconData)).rejects.toThrow(); - }); - }); +const request = require('supertest'); +const app = require('./app'); +const Subreddit = require('./models/subreddit'); + +describe('DELETE /delete_sr_banner', () => { + it('should delete the subreddit banner', async () => { + // Create a test subreddit + const subreddit = new Subreddit({ name: 'test_subreddit' }); + await subreddit.save(); + + // Make a DELETE request to delete the subreddit banner + const response = await request(app) + .delete('/delete_sr_banner') + .send({ subredditId: subreddit._id }); + + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Subreddit banner deleted successfully'); + + // Fetch the subreddit from the database and check if the banner is deleted + const updatedSubreddit = await Subreddit.findById(subreddit._id); + expect(updatedSubreddit.banner).toBeNull(); + }); +}); + +describe('DELETE /delete_sr_icon', () => { + it('should delete the subreddit icon', async () => { + // Create a test subreddit + const subreddit = new Subreddit({ name: 'test_subreddit' }); + await subreddit.save(); + + // Make a DELETE request to delete the subreddit icon + const response = await request(app) + .delete('/delete_sr_icon') + .send({ subredditId: subreddit._id }); + + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Subreddit icon deleted successfully'); + + // Fetch the subreddit from the database and check if the icon is deleted + const updatedSubreddit = await Subreddit.findById(subreddit._id); + expect(updatedSubreddit.icon).toBeNull(); + }); +}); + +describe('POST /upload_sr_icon', () => { + it('should upload the subreddit icon', async () => { + // Create a test subreddit + const subreddit = new Subreddit({ name: 'test_subreddit' }); + await subreddit.save(); + + // Icon data to be sent in the request + const iconData = 'icon_data_here'; + + // Make a POST request to upload the subreddit icon + const response = await request(app) + .post('/upload_sr_icon') + .send({ subredditId: subreddit._id, icon: iconData }); + + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Subreddit icon uploaded successfully'); + + // Fetch the subreddit from the database and check if the icon is uploaded + const updatedSubreddit = await Subreddit.findById(subreddit._id); + expect(updatedSubreddit.icon).toBe(iconData); + }); }); + From 012340ce98da76cfcb27140c8dd3bb85cc89459b Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 02:30:29 +0300 Subject: [PATCH 27/34] Create mine;where,mine;moderator --- mine;where,mine;moderator | 85 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 mine;where,mine;moderator diff --git a/mine;where,mine;moderator b/mine;where,mine;moderator new file mode 100644 index 0000000..47fc7d8 --- /dev/null +++ b/mine;where,mine;moderator @@ -0,0 +1,85 @@ +const express = require('express'); +const mongoose = require('mongoose'); +const bodyParser = require('body-parser'); +const jwt = require('jsonwebtoken'); +const Subreddit = require('./models/subreddit'); + +const app = express(); +app.use(bodyParser.json()); + +// Connect to MongoDB +mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true }) + .then(() => console.log('MongoDB connected')) + .catch(err => console.error('MongoDB connection error:', err)); + + +async function authenticateUser(req, res, next) { + try { + + const token = req.headers.authorization ? req.headers.authorization.split(' ')[1] : req.cookies.jwt; + + if (!token) { + return res.status(401).json({ error: 'Unauthorized: No token provided' }); + } + + const decoded = jwt.verify(token, process.env.JWT_SECRET); + + const user = await userModel.findById(decoded.userID); + + if (!user) { + return res.status(401).json({ error: 'Unauthorized: User not found' }); + } + + req.user = user; + + next(); + } catch (error) { + console.error('Authentication error:', error); + return res.status(401).json({ error: 'Unauthorized: Invalid token' }); + } +} + +// Task: mine/where +app.post('/mine/where', authenticateUser, async (req, res) => { + try { + const { subredditId, filter } = req.body; + // Check if the request body contains required fields + if (!subredditId || !filter) { + return res.status(400).json({ error: 'Subreddit ID and filter are required' }); + } + // Find the subreddit by ID + const subreddit = await Subreddit.findById(subredditId); + if (!subreddit) { + return res.status(404).json({ error: 'Subreddit not found' }); + } + + let filteredPosts; + if (filter === 'new') { + filteredPosts = await Post.find({ subreddit: subredditId }).sort({ createdAt: -1 }); + } else if (filter === 'top') { + filteredPosts = await Post.find({ subreddit: subredditId }).sort({ upvotes: -1 }); + } else { + return res.status(400).json({ error: 'Invalid filter criteria' }); + } + return res.status(200).json({ posts: filteredPosts }); + } catch (error) { + console.error('Error in mine/where:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + +// Task: mine/moderator +app.get('/mine/moderator', authenticateUser, async (req, res) => { + try { + // Find subreddits where the current user is a moderator + const moderatorSubreddits = await Subreddit.find({ moderators: req.user._id }); + return res.status(200).json({ subreddits: moderatorSubreddits }); + } catch (error) { + console.error('Error in mine/moderator:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + +app.listen(3000, () => { + console.log('Server is running on port 3000'); +}); From b9c0f7befd0c757c5410dec2216626383a29b9a6 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 02:31:58 +0300 Subject: [PATCH 28/34] Create test mine;where,mine;moderator --- test mine;where,mine;moderator | 47 ++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 test mine;where,mine;moderator diff --git a/test mine;where,mine;moderator b/test mine;where,mine;moderator new file mode 100644 index 0000000..9b451f9 --- /dev/null +++ b/test mine;where,mine;moderator @@ -0,0 +1,47 @@ +//test +const request = require('supertest'); +const app = require('./app'); +const Subreddit = require('./models/subreddit'); +const Post = require('./models/post'); + +describe('POST /mine/where', () => { + it('should filter posts based on the provided criteria', async () => { + // Create a test subreddit + const subreddit = new Subreddit({ name: 'test_subreddit' }); + await subreddit.save(); + + // Create test posts for the subreddit + const post1 = new Post({ title: 'Post 1', subreddit: subreddit._id }); + const post2 = new Post({ title: 'Post 2', subreddit: subreddit._id }); + await post1.save(); + await post2.save(); + + // Make a POST request to filter posts + const response = await request(app) + .post('/mine/where') + .send({ subredditId: subreddit._id, filter: 'new' }); + + // Expect response status to be 200 and check the number of returned posts + expect(response.status).toBe(200); + expect(response.body.posts.length).toBe(2); + }); +}); + +describe('GET /mine/moderator', () => { + it('should return subreddits where the user is a moderator', async () => { + // Create test subreddits + const subreddit1 = new Subreddit({ name: 'subreddit1', moderators: ['user1'] }); + const subreddit2 = new Subreddit({ name: 'subreddit2', moderators: ['user2'] }); + await subreddit1.save(); + await subreddit2.save(); + + // Make a GET request to fetch moderator subreddits + const response = await request(app) + .get('/mine/moderator') + .set('Authorization', 'Bearer '); + + // Expect response status to be 200 and check the number of returned subreddits + expect(response.status).toBe(200); + expect(response.body.subreddits.length).toBe(1); + }); +}); From 54e00b26a217e8c6afe931ed9721e4eac4c3ae3d Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 02:37:26 +0300 Subject: [PATCH 29/34] Create all the about --- all the about | 147 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 all the about diff --git a/all the about b/all the about new file mode 100644 index 0000000..d76aa9a --- /dev/null +++ b/all the about @@ -0,0 +1,147 @@ +const express = require('express'); +const mongoose = require('mongoose'); +const bodyParser = require('body-parser'); +const jwt = require('jsonwebtoken'); +const Subreddit = require('./models/subreddit'); + +const app = express(); +app.use(bodyParser.json()); + +// Connect to MongoDB +mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true }) + .then(() => console.log('MongoDB connected')) + .catch(err => console.error('MongoDB connection error:', err)); + +async function authenticateUser(req, res, next) { + try { + + const token = req.headers.authorization ? req.headers.authorization.split(' ')[1] : req.cookies.jwt; + + if (!token) { + return res.status(401).json({ error: 'Unauthorized: No token provided' }); + } + + const decoded = jwt.verify(token, process.env.JWT_SECRET); + + const user = await userModel.findById(decoded.userID); + + if (!user) { + return res.status(401).json({ error: 'Unauthorized: User not found' }); + } + + req.user = user; + + next(); + } catch (error) { + console.error('Authentication error:', error); + return res.status(401).json({ error: 'Unauthorized: Invalid token' }); + } +} + +// Task: about/Where +app.post('/about/where', authenticateUser, async (req, res) => { + try { + + const location = req.user.location; + return res.status(200).json({ location }); + } catch (error) { + console.error('Error:', error); + return res.status(500).json({ error: 'Internal server error' }); + } + }); + + // Task: about/Banned + app.post('/about/banned', authenticateUser, async (req, res) => { + try { + + const bannedUsers = await Ban.find(); + return res.status(200).json({ bannedUsers }); + } catch (error) { + console.error('Error:', error); + return res.status(500).json({ error: 'Internal server error' }); + } + }); + + // Task: about/Muted + app.post('/about/muted', authenticateUser, async (req, res) => { + try { + + const mutedUsers = await Mute.find(); + return res.status(200).json({ mutedUsers }); + } catch (error) { + console.error('Error:', error); + return res.status(500).json({ error: 'Internal server error' }); + } + }); + + // Task: about/Moderators + app.post('/about/moderators', authenticateUser, async (req, res) => { + try { + + const moderators = await Moderator.find({ subreddit: req.body.subredditId }); + return res.status(200).json({ moderators }); + } catch (error) { + console.error('Error:', error); + return res.status(500).json({ error: 'Internal server error' }); + } + }); + + // Task: about/Location + app.post('/about/location', authenticateUser, async (req, res) => { + try { + + const locationData = await Location.find({ coordinates: req.body.coordinates }); + return res.status(200).json({ locationData }); + } catch (error) { + console.error('Error:', error); + return res.status(500).json({ error: 'Internal server error' }); + } + }); + + // Task: about/Reports + app.post('/about/reports', authenticateUser, async (req, res) => { + try { + + const reports = await Report.find(); + return res.status(200).json({ reports }); + } catch (error) { + console.error('Error:', error); + return res.status(500).json({ error: 'Internal server error' }); + } + }); + + // Task: about/Spam + app.post('/about/spam', authenticateUser, async (req, res) => { + try { + + const spam = await Spam.find(); + return res.status(200).json({ spam }); + } catch (error) { + console.error('Error:', error); + return res.status(500).json({ error: 'Internal server error' }); + } + }); + + // Task: about/Modqueue + app.post('/about/modqueue', authenticateUser, async (req, res) => { + try { + + const modqueue = await Modqueue.find(); + return res.status(200).json({ modqueue }); + } catch (error) { + console.error('Error:', error); + return res.status(500).json({ error: 'Internal server error' }); + } + }); + + // Task: about/Unmoderated + app.post('/about/unmoderated', authenticateUser, async (req, res) => { + try { + + const unmoderated = await Unmoderated.find(); + return res.status(200).json({ unmoderated }); + } catch (error) { + console.error('Error:', error); + return res.status(500).json({ error: 'Internal server error' }); + } + }); From eb3335e4622c9739f0d8da06b2bef9eca603c001 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 02:55:21 +0300 Subject: [PATCH 30/34] Create test all the about --- test all the about | 138 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 test all the about diff --git a/test all the about b/test all the about new file mode 100644 index 0000000..8dd3968 --- /dev/null +++ b/test all the about @@ -0,0 +1,138 @@ +const request = require('supertest'); +const app = require('./app'); +const Ban = require('./models/ban'); +const Mute = require('./models/mute'); +const Moderator = require('./models/moderator'); +const LocationData = require('./models/locationData'); +const Report = require('./models/report'); +const Spam = require('./models/spam'); +const Modqueue = require('./models/modqueue'); +const Unmoderated = require('./models/unmoderated'); + +describe('POST /about/where', () => { + it('should return user location', async () => { + // Make a POST request to get user location + const response = await request(app) + .post('/about/where') + .set('Authorization', 'Bearer YOUR_TOKEN_HERE'); + + // Expect response status to be 200 and check the location + expect(response.status).toBe(200); + expect(response.body.location).toBeDefined(); + + }); +}); + +describe('GET /about/banned', () => { + it('should return list of banned users', async () => { + // Make a GET request to get list of banned users + const response = await request(app) + .get('/about/banned') + .set('Authorization', 'Bearer YOUR_TOKEN_HERE'); + + // Expect response status to be 200 and check the list of banned users + expect(response.status).toBe(200); + expect(response.body.bannedUsers).toBeDefined(); + + }); +}); + +describe('GET /about/muted', () => { + it('should return list of muted users', async () => { + // Make a GET request to get list of muted users + const response = await request(app) + .get('/about/muted') + .set('Authorization', 'Bearer YOUR_TOKEN_HERE'); + + // Expect response status to be 200 and check the list of muted users + expect(response.status).toBe(200); + expect(response.body.mutedUsers).toBeDefined(); + + }); +}); + +describe('GET /about/moderators', () => { + it('should return list of moderators', async () => { + // Make a GET request to get list of moderators + const response = await request(app) + .get('/about/moderators') + .set('Authorization', 'Bearer YOUR_TOKEN_HERE'); + + // Expect response status to be 200 and check the list of moderators + expect(response.status).toBe(200); + expect(response.body.moderators).toBeDefined(); + + }); +}); + +describe('GET /about/location', () => { + it('should return location details', async () => { + // Make a GET request to get location details + const response = await request(app) + .get('/about/location') + .set('Authorization', 'Bearer YOUR_TOKEN_HERE'); + + // Expect response status to be 200 and check the location details + expect(response.status).toBe(200); + expect(response.body.locationDetails).toBeDefined(); + + }); +}); + +describe('GET /about/reports', () => { + it('should return list of reports', async () => { + // Make a GET request to get list of reports + const response = await request(app) + .get('/about/reports') + .set('Authorization', 'Bearer YOUR_TOKEN_HERE'); + + // Expect response status to be 200 and check the list of reports + expect(response.status).toBe(200); + expect(response.body.reports).toBeDefined(); + + }); +}); + +describe('GET /about/spam', () => { + it('should return list of spam posts', async () => { + // Make a GET request to get list of spam posts + const response = await request(app) + .get('/about/spam') + .set('Authorization', 'Bearer YOUR_TOKEN_HERE'); + + // Expect response status to be 200 and check the list of spam posts + expect(response.status).toBe(200); + expect(response.body.spamPosts).toBeDefined(); + + }); +}); + +describe('GET /about/modqueue', () => { + it('should return list of posts in moderation queue', async () => { + // Make a GET request to get list of posts in moderation queue + const response = await request(app) + .get('/about/modqueue') + .set('Authorization', 'Bearer YOUR_TOKEN_HERE'); + + // Expect response status to be 200 and check the list of posts in modqueue + expect(response.status).toBe(200); + expect(response.body.modqueuePosts).toBeDefined(); + + }); +}); + +describe('GET /about/unmoderated', () => { + it('should return list of unmoderated posts', async () => { + // Make a GET request to get list of unmoderated posts + const response = await request(app) + .get('/about/unmoderated') + .set('Authorization', 'Bearer YOUR_TOKEN_HERE'); + + // Expect response status to be 200 and check the list of unmoderated posts + expect(response.status).toBe(200); + expect(response.body.unmoderatedPosts).toBeDefined(); + + }); +}); + + From 307f5da16a94a1704ff828359b2b97cfd1fed276 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 03:04:00 +0300 Subject: [PATCH 31/34] Update approve,remove,show_comment,leavemoderator,accept_moderator_invite --- ...ent,leavemoderator,accept_moderator_invite | 155 ++++++++++++------ 1 file changed, 106 insertions(+), 49 deletions(-) diff --git a/approve,remove,show_comment,leavemoderator,accept_moderator_invite b/approve,remove,show_comment,leavemoderator,accept_moderator_invite index abaa942..1835c78 100644 --- a/approve,remove,show_comment,leavemoderator,accept_moderator_invite +++ b/approve,remove,show_comment,leavemoderator,accept_moderator_invite @@ -1,51 +1,108 @@ -const CommentModel = require('../models/CommentModel'); - -exports.approve = async (req, res, next) => { - try { - const { id } = req.params; - await CommentModel.approve(id); - res.status(200).json({ message: 'Item approved successfully.' }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}; - -exports.remove = async (req, res, next) => { - try { - const { id } = req.params; - await CommentModel.remove(id); - res.status(200).json({ message: 'Item removed successfully.' }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}; - -exports.showComment = async (req, res, next) => { - try { - const { commentId } = req.params; - await CommentModel.show(commentId); - res.status(200).json({ message: 'Comment shown successfully.' }); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}; - -exports.leaveModerator = async (req, res, next) => { - try { - const { subredditName } = req.params; - await CommentModel.leaveModerator(subredditName); - res.status(200).json({ message: 'Left moderatorship successfully.' }); - } catch (error) { - res.status(500).json({ error: error.message }); +const express = require('express'); +const mongoose = require('mongoose'); +const bodyParser = require('body-parser'); +const jwt = require('jsonwebtoken'); +const User = require('./models/user'); +const Item = require('./models/item'); +const Comment = require('./models/comment'); +const Moderator = require('./models/moderator'); + +const app = express(); +app.use(bodyParser.json()); + +// Connect to MongoDB +mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true }) + .then(() => console.log('MongoDB connected')) + .catch(err => console.error('MongoDB connection error:', err)); + +async function authenticateUser(req, res, next) { + try { + const token = req.headers.authorization ? req.headers.authorization.split(' ')[1] : req.cookies.jwt; + + if (!token) { + return res.status(401).json({ error: 'Unauthorized: No token provided' }); } -}; - -exports.acceptModeratorInvite = async (req, res, next) => { - try { - const { subredditName } = req.params; - await CommentModel.acceptModeratorInvite(subredditName); - res.status(200).json({ message: 'Moderator invitation accepted successfully.' }); - } catch (error) { - res.status(500).json({ error: error.message }); + + const decoded = jwt.verify(token, process.env.JWT_SECRET); + const user = await User.findById(decoded.userID); + + if (!user) { + return res.status(401).json({ error: 'Unauthorized: User not found' }); } -}; + + req.user = user; + + next(); + } catch (error) { + console.error('Authentication error:', error); + return res.status(401).json({ error: 'Unauthorized: Invalid token' }); + } +} + +// Task: approve +app.put('/approve', authenticateUser, async (req, res) => { + try { + const { itemId } = req.body; + + await Item.findByIdAndUpdate(itemId, { approved: true }); + return res.status(200).json({ message: 'Approved successfully' }); + } catch (error) { + console.error('Error approving:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + +// Task: remove +app.put('/remove', authenticateUser, async (req, res) => { + try { + const { itemId } = req.body; + + await Item.findByIdAndDelete(itemId); + return res.status(200).json({ message: 'Removed successfully' }); + } catch (error) { + console.error('Error removing:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + +// Task: show_comment +app.get('/show_comment', authenticateUser, async (req, res) => { + try { + const { commentId } = req.query; + + const comment = await Comment.findById(commentId); + return res.status(200).json({ message: 'Comment shown successfully', comment }); + } catch (error) { + console.error('Error showing comment:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + +// Task: leavemoderator +app.post('/leavemoderator', authenticateUser, async (req, res) => { + try { + const { subredditId } = req.body; + + await Moderator.findOneAndRemove({ user: req.user._id, subreddit: subredditId }); + return res.status(200).json({ message: 'Moderator left successfully' }); + } catch (error) { + console.error('Error leaving moderator:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + +// Task: accept_moderator_invite +app.post('/accept_moderator_invite', authenticateUser, async (req, res) => { + try { + const { subredditId } = req.body; + + const moderator = new Moderator({ user: req.user._id, subreddit: subredditId }); + await moderator.save(); + return res.status(200).json({ message: 'Moderator invitation accepted successfully' }); + } catch (error) { + console.error('Error accepting moderator invitation:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + +module.exports = app; From 9b4802bb1d5e76cfaba3e36dbb65f8e40760b735 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 03:05:46 +0300 Subject: [PATCH 32/34] Update test approve,remove,show_comment,leavemoderator,accept_moderator_invite --- ...ent,leavemoderator,accept_moderator_invite | 130 +++++++++--------- 1 file changed, 67 insertions(+), 63 deletions(-) diff --git a/test approve,remove,show_comment,leavemoderator,accept_moderator_invite b/test approve,remove,show_comment,leavemoderator,accept_moderator_invite index 2b6dd5c..c940bae 100644 --- a/test approve,remove,show_comment,leavemoderator,accept_moderator_invite +++ b/test approve,remove,show_comment,leavemoderator,accept_moderator_invite @@ -1,74 +1,78 @@ -const { - approve, - remove, - show_comment, - leave_moderator, - accept_moderator_invite -} = require('./subredditFunctions'); +const request = require('supertest'); +const app = require('./app'); +const Subreddit = require('./models/subreddit'); -describe('Subreddit Functions', () => { - describe('approve', () => { - it('should approve a comment or submission', async () => { - const id = 'example_id'; - const result = await approve(id); - expect(result).toEqual({ message: 'Item approved successfully.' }); - }); +describe('POST /approve', () => { + it('should approve something', async () => { + // Make a POST request to approve something + const response = await request(app) + .post('/approve') + .send({ itemId: 'ITEM_ID_TO_APPROVE' }); - it('should handle errors gracefully', async () => { - const invalidId = 'invalid_id'; - await expect(approve(invalidId)).rejects.toThrow(); - }); - }); + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Approved successfully'); - describe('remove', () => { - it('should remove a comment or submission', async () => { - const id = 'example_id'; - const result = await remove(id); - expect(result).toEqual({ message: 'Item removed successfully.' }); - }); + + }); +}); + +describe('POST /remove', () => { + it('should remove something', async () => { + // Make a POST request to remove something + const response = await request(app) + .post('/remove') + .send({ itemId: 'ITEM_ID_TO_REMOVE' }); - it('should handle errors gracefully', async () => { - const invalidId = 'invalid_id'; - await expect(remove(invalidId)).rejects.toThrow(); - }); - }); + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Removed successfully'); - describe('show_comment', () => { - it('should show a comment', async () => { - const commentId = 'example_comment_id'; - const result = await show_comment(commentId); - expect(result).toEqual({ message: 'Comment shown successfully.' }); - }); + + }); +}); - it('should handle errors gracefully', async () => { - const invalidCommentId = 'invalid_comment_id'; - await expect(show_comment(invalidCommentId)).rejects.toThrow(); - }); - }); +describe('GET /show_comment', () => { + it('should show a comment', async () => { + // Make a GET request to show a comment + const response = await request(app) + .get('/show_comment') + .query({ commentId: 'COMMENT_ID_TO_SHOW' }); - describe('leave_moderator', () => { - it('should leave moderatorship of a subreddit', async () => { - const subredditName = 'example_subreddit'; - const result = await leave_moderator(subredditName); - expect(result).toEqual({ message: 'Moderatorship left successfully.' }); - }); + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Comment shown successfully'); + + + }); +}); + +describe('POST /leavemoderator', () => { + it('should leave moderator role', async () => { + // Make a POST request to leave moderator role + const response = await request(app) + .post('/leavemoderator') + .send({ subredditId: 'SUBREDDIT_ID_TO_LEAVE_MODERATOR' }); + + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Moderator left successfully'); + + + }); +}); - it('should handle errors gracefully', async () => { - const invalidSubredditName = 'invalid_subreddit'; - await expect(leave_moderator(invalidSubredditName)).rejects.toThrow(); - }); - }); +describe('POST /accept_moderator_invite', () => { + it('should accept moderator invitation', async () => { + // Make a POST request to accept moderator invitation + const response = await request(app) + .post('/accept_moderator_invite') + .send({ subredditId: 'SUBREDDIT_ID_TO_ACCEPT_INVITE' }); - describe('accept_moderator_invite', () => { - it('should accept a moderator invitation', async () => { - const subredditName = 'example_subreddit'; - const result = await accept_moderator_invite(subredditName); - expect(result).toEqual({ message: 'Moderator invitation accepted successfully.' }); - }); + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Moderator invitation accepted successfully'); - it('should handle errors gracefully', async () => { - const invalidSubredditName = 'invalid_subreddit'; - await expect(accept_moderator_invite(invalidSubredditName)).rejects.toThrow(); - }); - }); + + }); }); From 3a2436aa8fdc1af33538219a53608b5ff77c8fd1 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 03:30:54 +0300 Subject: [PATCH 33/34] Update site_admin;about;edite --- site_admin;about;edite | 92 +++++++++++++++++++++++++++++++++--------- 1 file changed, 74 insertions(+), 18 deletions(-) diff --git a/site_admin;about;edite b/site_admin;about;edite index 63df42a..765f33b 100644 --- a/site_admin;about;edite +++ b/site_admin;about;edite @@ -1,20 +1,76 @@ -const AdminModel = require('../models/AdminModel'); - -exports.siteAdmin = async (req, res, next) => { - try { - const adminInfo = await AdminModel.getAdminInfo(); - res.status(200).json(adminInfo); - } catch (error) { - res.status(500).json({ error: error.message }); +const express = require('express'); +const mongoose = require('mongoose'); +const bodyParser = require('body-parser'); +const jwt = require('jsonwebtoken'); +const Subreddit = require('./models/subreddit'); + +const app = express(); +app.use(bodyParser.json()); + +// Connect to MongoDB +mongoose.connect('mongodb://localhost:27017/myapp', { useNewUrlParser: true, useUnifiedTopology: true }) + .then(() => console.log('MongoDB connected')) + .catch(err => console.error('MongoDB connection error:', err)); + +async function authenticateUser(req, res, next) { + try { + + const token = req.headers.authorization ? req.headers.authorization.split(' ')[1] : req.cookies.jwt; + + if (!token) { + return res.status(401).json({ error: 'Unauthorized: No token provided' }); + } + + const decoded = jwt.verify(token, process.env.JWT_SECRET); + + + const user = await userModel.findById(decoded.userID); + + if (!user) { + return res.status(401).json({ error: 'Unauthorized: User not found' }); } -}; - -exports.editAbout = async (req, res, next) => { - try { - const { subredditName, aboutText } = req.body; - await AdminModel.editAbout(subredditName, aboutText); - res.status(200).json({ message: 'Subreddit about section edited successfully.' }); - } catch (error) { - res.status(500).json({ error: error.message }); + + + req.user = user; + + next(); + } catch (error) { + console.error('Authentication error:', error); + return res.status(401).json({ error: 'Unauthorized: Invalid token' }); + } +} + +// Task: site_admin +app.post('/site_admin', authenticateUser, async (req, res) => { + try { + + if (req.user.isAdmin) { + return res.status(200).json({ message: 'Site admin task completed successfully' }); + } else { + return res.status(403).json({ error: 'Forbidden: User is not a site admin' }); + } + } catch (error) { + console.error('Error in site_admin task:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + +// Task: /about/edit +app.put('/about/edit', authenticateUser, async (req, res) => { + try { + + const { subredditId, aboutText } = req.body; + const subreddit = await Subreddit.findByIdAndUpdate(subredditId, { about: aboutText }); + if (!subreddit) { + return res.status(404).json({ error: 'Subreddit not found' }); } -}; + return res.status(200).json({ message: 'About section updated successfully' }); + } catch (error) { + console.error('Error in /about/edit task:', error); + return res.status(500).json({ error: 'Internal server error' }); + } +}); + + +module.exports = app; + From ea6964e4544b44b3469458b458bbae3f598ca2f8 Mon Sep 17 00:00:00 2001 From: yaso-2001 <160578525+yaso-2001@users.noreply.github.com> Date: Fri, 10 May 2024 03:32:24 +0300 Subject: [PATCH 34/34] Update test site_admin;about;edite --- test site_admin;about;edite | 77 ++++++++++++++++++++++--------------- 1 file changed, 45 insertions(+), 32 deletions(-) diff --git a/test site_admin;about;edite b/test site_admin;about;edite index cf2a0e0..26ba3f3 100644 --- a/test site_admin;about;edite +++ b/test site_admin;about;edite @@ -1,35 +1,48 @@ -const { - site_admin, - edit_about -} = require('./subredditFunctions'); +const request = require('supertest'); +const app = require('./app'); +const UserModel = require('./models/user'); +const AboutModel = require('./models/about'); -describe('Subreddit Functions', () => { - describe('site_admin', () => { - it('should retrieve site admin information', async () => { - const adminInfo = await site_admin(); - expect(adminInfo).toBeDefined(); - - }); - - it('should handle errors gracefully', async () => { - await expect(site_admin()).rejects.toThrow(); - - }); +describe('POST /site_admin', () => { + it('should perform site admin tasks', async () => { + + const user = new UserModel({ username: 'admin', isAdmin: true }); + await user.save(); + + // Authenticate the user and get the JWT token + const token = jwt.sign({ userID: user._id }, process.env.JWT_SECRET); + + // Make a POST request to perform site admin tasks + const response = await request(app) + .post('/site_admin') + .set('Authorization', `Bearer ${token}`) + .send({ userId: 'user_id_here', role: 'admin' }); // Example request body + + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('Site admin task completed successfully'); + + }); - - describe('edit_about', () => { - it('should edit the about section of a subreddit', async () => { - const subredditName = 'example_subreddit'; - const aboutText = 'New about text for the subreddit.'; - const result = await edit_about(subredditName, aboutText); - expect(result).toEqual({ message: 'About section edited successfully.' }); - }); - - it('should handle errors gracefully', async () => { - const subredditName = 'invalid_subreddit'; - const aboutText = 'New about text for the subreddit.'; - await expect(edit_about(subredditName, aboutText)).rejects.toThrow(); - - }); + }); + + describe('PUT /about/edit', () => { + it('should edit the about page', async () => { + + const aboutContent = 'This is the updated about page content'; + + // Make a PUT request to edit the about page + const response = await request(app) + .put('/about/edit') + .send({ content: aboutContent }); // Example request body + + // Expect response status to be 200 and check the message + expect(response.status).toBe(200); + expect(response.body.message).toBe('About page updated successfully'); + + // Fetch the about page content from the database and check if it's updated + const updatedAbout = await AboutModel.findOne(); + expect(updatedAbout.content).toBe(aboutContent); }); -}); + }); +