Skip to content
This repository has been archived by the owner on Jul 17, 2023. It is now read-only.

Commit

Permalink
Merge branch 'release/1.0.6'
Browse files Browse the repository at this point in the history
  • Loading branch information
cawa-93 committed Aug 14, 2019
2 parents 00bf0bf + b8abc4f commit b187dcd
Show file tree
Hide file tree
Showing 17 changed files with 137 additions and 48 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
![Chrome Web Store](https://img.shields.io/chrome-web-store/users/eopmgkejoplocjnpljjhgbeadjoomcbd?label=%D0%9F%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D0%B5%D0%B9&style=flat)
![Chrome Web Store](https://img.shields.io/chrome-web-store/v/eopmgkejoplocjnpljjhgbeadjoomcbd?label=%D0%92%D0%B5%D1%80%D1%81%D0%B8%D1%8F&style=flat)

| ![Внешний вид кнопки "Смотреть онлайн"](promo/watch-button.png) | ![Внешний вид плеера](promo/player.png) | ![Внешний вид плеера](promo/comments.png) |
| ------------- |:-------------:| -----:|
![Внешний вид кнопки "Смотреть онлайн"](promo/main.png) | ![Внешний вид кнопки "Смотреть онлайн"](promo/episodes.png)
--- | ---
![Внешний вид кнопки "Смотреть онлайн"](promo/translations.png) | ![Внешний вид кнопки "Смотреть онлайн"](promo/comments.png)

Это браузерное расширение, которое позволяет вам смотреть аниме онлайн и синхронизировать его с вашим списком на Шикимори.

Expand Down
1 change: 0 additions & 1 deletion build/generate_manifest.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ const manimest = {
permissions: [
'https://shikimori.one/*',
'https://shikimori.org/*',
'https://smotretanime.ru/*',
'https://smotret-anime-365.ru/*',
'https://api.jikan.moe/*',
'webRequest',
Expand Down
20 changes: 10 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "play-shikimori-online",
"version": "1.0.5",
"version": "1.0.6",
"description": "Расширение позволяет смотреть аниме онлайн и синхронизировать его с вашим списком на Шикимори (shikimori.org и shikimori.one)",
"main": "index.js",
"type": "module",
Expand All @@ -9,21 +9,21 @@
"npm": "6.9"
},
"dependencies": {
"@mdi/font": "^3.9.97",
"@mdi/font": "^4.0.96",
"@sentry/browser": "^5.6.1",
"@sentry/integrations": "^5.6.1",
"async-retry": "^1.2.3",
"kv-storage-polyfill": "^1.1.0",
"vue": "^2.6.10",
"vue-analytics": "^5.17.0",
"vue-router": "^3.1.2",
"vuetify": "^2.0.5",
"vuetify": "^2.0.7",
"vuex": "^3.1.1"
},
"devDependencies": {
"@babel/preset-env": "^7.5.5",
"@sentry/cli": "^1.47.1",
"@types/video.js": "^7.2.11",
"@types/video.js": "^7.2.12",
"archiver": "^3.1.1",
"chrome-webstore-upload": "^0.2.2",
"dotenv": "^8.0.0",
Expand Down
Binary file modified promo/comments.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added promo/episodes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added promo/main.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed promo/player.png
Binary file not shown.
Binary file added promo/translations.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed promo/watch-button.png
Binary file not shown.
44 changes: 34 additions & 10 deletions src/UI/components/comments.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<template>
<section class="comments-container">
<section class="comments-container" v-if="allowComments">
<div class="display-1 mt-6 mb-4 d-flex topic-title">
<h2 class="display-1"
@click="$vuetify.goTo($refs['comments-feed'], {duration: 300})">
Expand Down Expand Up @@ -94,7 +94,9 @@
</div>
</div>

<p class="pl-0 blockquote" v-else>Ты можешь написать комментарий первым, если поторопишься 😁</p>
<p class="pl-0 blockquote"
v-else
ref="comments-feed">Ты можешь написать комментарий первым, если поторопишься 😁</p>

<v-form @submit.prevent="createComment" class="mt-7" v-if="user">
<v-textarea
Expand Down Expand Up @@ -134,6 +136,7 @@
data() {
return {
layout: {
loading: true,
moreComments: {
Expand Down Expand Up @@ -161,6 +164,10 @@
currentEpisode() {
return this.$store.state.player.currentEpisode
},
allowComments() {
return this.currentEpisode && this.currentEpisode.episodeInt % 1 === 0
},
},
methods: {
Expand All @@ -169,16 +176,28 @@
},
async init() {
if (!this.currentEpisode) return
this.topic = null
this.comments.items = []
this.comments.page = 1
if (!this.allowComments) return
this.layout.loading = true
const topics = await shikimoriAPI(
`/animes/${this.currentEpisode.myAnimelist}/topics?kind=episode&episode=${this.currentEpisode.episodeInt}`,
)
this.topic = topics[0]
this.comments.items = []
this.comments.page = 1
try {
const topics = await shikimoriAPI(
`/animes/${this.currentEpisode.myAnimelist}/topics?kind=episode&episode=${this.currentEpisode.episodeInt}`,
)
this.topic = topics[0]
this.comments.items = []
this.comments.page = 1
} catch (e) {
window.Sentry.captureException(e)
console.error(e)
}
await this.loadComments()
Expand All @@ -200,14 +219,19 @@
const date = new Date(iso)
const now = new Date()
const diff = date - now
const formatter = new Intl.RelativeTimeFormat()
const msPerMinute = 60 * 1000
const msPerHour = msPerMinute * 60
const msPerDay = msPerHour * 24
const msPerMonth = msPerDay * 30
const msPerYear = msPerDay * 365
if (diff / msPerMonth < -1 || !Intl || typeof Intl.RelativeTimeFormat !== 'function') {
return date.toLocaleString()
}
const formatter = new Intl.RelativeTimeFormat()
if (Math.abs(diff) < msPerMinute) {
return formatter.format(Math.round(diff / 1000), 'seconds')
}
Expand Down
45 changes: 36 additions & 9 deletions src/background/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ async function loadRuntimeMessages(minTimestamp, broadcastType = 'broadcast', ma
const commentWithMessages = []
let page = 1
let lastCommentTimestamp = Date.now()
while (minTimestamp <= lastCommentTimestamp && commentWithMessages.length < maxLoadedMessages) {
try {
try {
while (minTimestamp <= lastCommentTimestamp && commentWithMessages.length < maxLoadedMessages) {
const {response: comments, error} = await makeRequest({
url: `https://shikimori.one/api/comments/?desc=1&commentable_id=285393&commentable_type=Topic&limit=100&page=${page++}`,
options: {
Expand Down Expand Up @@ -117,13 +117,10 @@ async function loadRuntimeMessages(minTimestamp, broadcastType = 'broadcast', ma
),
)

} catch (error) {
console.error(`Can't check broadcast message`, {error})
Sentry.captureException(error)
if (error.error === 'not-granted') {
break
}
}
} catch (error) {
console.error(`Can't check broadcast message`, {error})
Sentry.captureException(error)
}

if (commentWithMessages.length) {
Expand Down Expand Up @@ -187,7 +184,25 @@ async function makeRequest({url, options}) {
// if (options && options.method && options.method === 'GET' && options.maxAge) {
// }

const isGranted = await isPermissionsGranted(url)
let isGranted = await isPermissionsGranted(url)

if (!isGranted) {
try {
isGranted = await requestPermissions([
'webRequest',
'webRequestBlocking',
'storage',
'tabs',
], [
'https://shikimori.one/*',
'https://shikimori.org/*',
'https://smotret-anime-365.ru/*',
'https://api.jikan.moe/*',
])
} catch (e) {
}
}

if (!isGranted) {
return {
error: {
Expand Down Expand Up @@ -230,6 +245,18 @@ function isPermissionsGranted(url) {
}


function requestPermissions(permissions = [], origins = []) {
return new Promise(resolve => {
chrome.permissions.request({
permissions,
origins,
},
resolve,
)
})
}


/**
* Выполняет указанный запрос и в случае ошибки повторяет попытку
* @param {*} request
Expand Down
11 changes: 10 additions & 1 deletion src/content-scripts/anime365-player-events.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,16 @@ try {
*/
const player = window.playerGlobal
if (!player) {
throw new Error(`window.playerGlobal is ${window.playerGlobal}`)
const waitUntilEmbedAvailable = document.body.querySelector('.wait-until-embed-available')
if (!waitUntilEmbedAvailable) {
throw new Error(`window.playerGlobal is ${window.playerGlobal}`) // Исключение обрабатывается в блоке catch
// ниже
}

const addUploadRequestForm = document.body.querySelector('form[action*="/translations/embedAddUploadRequest"]')
if (addUploadRequestForm) {
addUploadRequestForm.submit()
}
}
const seriesId = config.get('play-shikimori[seriesId]')
const episodeId = config.get('play-shikimori[episodeId]')
Expand Down
4 changes: 4 additions & 0 deletions src/content-scripts/watch-button.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ function getAnime() {
async function getEpisodes(myAnimeListId) {
/** @type {anime365.api.SeriesCollection} */
const {data: [series]} = await anime365API(`/series/?myAnimeListId=${myAnimeListId}`)
if (!series) {
return []
}

return filterEpisodes(series)
}

Expand Down
2 changes: 1 addition & 1 deletion src/helpers/filter-episodes.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export function filterEpisodes({episodes, type, numberOfEpisodes}) {
export function filterEpisodes({episodes, type, numberOfEpisodes} = {}) {
if (!episodes || !episodes.length) {
return []
}
Expand Down
35 changes: 26 additions & 9 deletions src/helpers/get-translation-priority.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,9 @@ export function getTypesPriority(translations) {
*
* @param {anime365.Translation[]} translations
* @param {string} authorsSummaryRaw
* @param {string} type
*/
export function filterTranslationsByAuthor(translations, authorsSummaryRaw) {
export function filterTranslationsByAuthor(translations, authorsSummaryRaw, type) {
const authorsSummary = clearAuthorSummary(authorsSummaryRaw)
if (!authorsSummary) {
return []
Expand All @@ -80,9 +81,13 @@ export function filterTranslationsByAuthor(translations, authorsSummaryRaw) {
return translations.filter(translation => {
const summary = clearAuthorSummary(translation.authorsSummary)

return summary && (
authorsSummary.indexOf(summary) >= 0 || summary.indexOf(authorsSummary) >= 0
)
return summary &&
(
authorsSummary.indexOf(summary) >= 0 || summary.indexOf(authorsSummary) >= 0
)
&& (
!type || type === translation.type
)

})
}
Expand Down Expand Up @@ -118,11 +123,12 @@ export function getMostPriorityTranslation(translations) {
export function getPriorityTranslationForEpisode(history, episode) {

// Выбираем перевод используемый для предыдущих серий
if (history.has(episode.seriesId)) {
const previousUserTranslation = history.get(episode.seriesId)

const previousUserTranslation = history.get(episode.seriesId)
const previousUserTranslationAuthor = previousUserTranslation ? previousUserTranslation.authorsSummary : null
const previousUserTranslationType = previousUserTranslation ? previousUserTranslation.type : null
if (previousUserTranslationAuthor) {
// Поиск перевода от того же автора
const priorityTranslations = filterTranslationsByAuthor(episode.translations, previousUserTranslation.authorsSummary)
const priorityTranslations = filterTranslationsByAuthor(episode.translations, previousUserTranslationAuthor, previousUserTranslationType)

// Если для текущей серии найден перевод того же автора что сохранен в истории — возвращаем
if (priorityTranslations.length) {
Expand All @@ -137,16 +143,27 @@ export function getPriorityTranslationForEpisode(history, episode) {
// Сортируем всех авторов в порядке популярности
.sort(([, rating1], [, rating2]) => rating2 - rating1)


// Перебираем всех авторов в порядке популярности
for (const [author] of authorPriorityMap) {
const filtered = filterTranslationsByAuthor(episode.translations, author)
const filtered = filterTranslationsByAuthor(episode.translations, author, previousUserTranslationType)

// Если перевод от одного из популярных авторов найден — вернуть его
if (filtered && filtered.length) {
return filtered
}
}

// Поиск перевода от того же типа что и сохраненный
if (previousUserTranslationType) {
const priorityTranslations = episode.translations.filter(t => t.type === previousUserTranslationType)

// Если для текущей серии найден перевод того же типа что сохранен в истории — возвращаем
if (priorityTranslations.length) {
return priorityTranslations
}
}

// Карта типов переводов и их индекс популярности
const typePriorityMap = [...getTypesPriority(history)]
// Не учитываем типы которые используються реже чем в 10% случаев
Expand Down
10 changes: 9 additions & 1 deletion src/helpers/shikimori-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,15 @@ export function shikimoriCallAPI(url, options = {}) {
},
({response, error}) => {
if (error) {
return reject(error)
if (!error.message
&& error.response
&& Array.isArray(error.response)
&& error.response.length === 1
&& typeof error.response[0] === 'string'
) {
error.message = error.response[0]
}
return reject(new Error(error))
}

resolve(response)
Expand Down

0 comments on commit b187dcd

Please sign in to comment.