mirror of
https://github.com/omnivore-app/omnivore.git
synced 2026-03-11 08:54:26 +00:00
Merge pull request #3458 from omnivore-app/main
Web production deployment
This commit is contained in:
commit
97ce5df993
72 changed files with 27628 additions and 1257 deletions
|
|
@ -59,7 +59,8 @@ import Views
|
|||
}
|
||||
|
||||
func handleGoogleAuth(authenticator: Authenticator) async {
|
||||
let googleAuthResponse = await authenticator.handleGoogleAuth()
|
||||
let presentingVC = presentingViewController()
|
||||
let googleAuthResponse = await authenticator.handleGoogleAuth(presentingVC: presentingVC)
|
||||
|
||||
switch googleAuthResponse {
|
||||
case let .loginError(error):
|
||||
|
|
@ -71,3 +72,15 @@ import Views
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor private func presentingViewController() -> PlatformViewController? {
|
||||
#if os(iOS)
|
||||
let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene
|
||||
return scene?.windows
|
||||
.filter(\.isKeyWindow)
|
||||
.first?
|
||||
.rootViewController
|
||||
#elseif os(macOS)
|
||||
return NSApplication.shared.windows.first
|
||||
#endif
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,9 +10,9 @@ public enum GoogleAuthResponse {
|
|||
}
|
||||
|
||||
extension Authenticator {
|
||||
public func handleGoogleAuth() async -> GoogleAuthResponse {
|
||||
public func handleGoogleAuth(presentingVC: PlatformViewController?) async -> GoogleAuthResponse {
|
||||
let idToken = await withCheckedContinuation { continuation in
|
||||
googleSignIn { continuation.resume(returning: $0) }
|
||||
googleSignIn(presenting: presentingVC) { continuation.resume(returning: $0) }
|
||||
}
|
||||
|
||||
guard let idToken = idToken else { return .loginError(error: .unauthorized) }
|
||||
|
|
@ -50,13 +50,7 @@ extension Authenticator {
|
|||
}
|
||||
}
|
||||
|
||||
func googleSignIn(completion: @escaping (String?) -> Void) {
|
||||
#if os(iOS)
|
||||
let presenting = presentingViewController()
|
||||
#else
|
||||
let presenting = NSApplication.shared.windows.first
|
||||
#endif
|
||||
|
||||
func googleSignIn(presenting: PlatformViewController?, completion: @escaping (String?) -> Void) {
|
||||
guard let presenting = presenting else {
|
||||
completion(nil)
|
||||
return
|
||||
|
|
@ -82,15 +76,3 @@ extension Authenticator {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func presentingViewController() -> PlatformViewController? {
|
||||
#if os(iOS)
|
||||
let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene
|
||||
return scene?.windows
|
||||
.filter(\.isKeyWindow)
|
||||
.first?
|
||||
.rootViewController
|
||||
#elseif os(macOS)
|
||||
return nil
|
||||
#endif
|
||||
}
|
||||
|
|
|
|||
|
|
@ -71,6 +71,7 @@
|
|||
"graphql-shield": "^7.5.0",
|
||||
"highlightjs": "^9.16.2",
|
||||
"html-entities": "^2.3.2",
|
||||
"image-size": "^1.0.2",
|
||||
"intercom-client": "^3.1.4",
|
||||
"ioredis": "^5.3.2",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
|
|
@ -155,4 +156,4 @@
|
|||
"volta": {
|
||||
"extends": "../../package.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,12 +7,22 @@ import {
|
|||
PrimaryGeneratedColumn,
|
||||
UpdateDateColumn,
|
||||
} from 'typeorm'
|
||||
import { SubscriptionStatus, SubscriptionType } from '../generated/graphql'
|
||||
import { NewsletterEmail } from './newsletter_email'
|
||||
import { User } from './user'
|
||||
|
||||
export const DEFAULT_SUBSCRIPTION_FOLDER = 'following'
|
||||
|
||||
export enum SubscriptionStatus {
|
||||
Active = 'ACTIVE',
|
||||
Deleted = 'DELETED',
|
||||
Unsubscribed = 'UNSUBSCRIBED',
|
||||
}
|
||||
|
||||
export enum SubscriptionType {
|
||||
Newsletter = 'NEWSLETTER',
|
||||
Rss = 'RSS',
|
||||
}
|
||||
|
||||
@Entity({ name: 'subscriptions' })
|
||||
export class Subscription {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
|
|
@ -59,7 +69,7 @@ export class Subscription {
|
|||
count!: number
|
||||
|
||||
@Column('timestamp', { nullable: true })
|
||||
lastFetchedAt?: Date | null
|
||||
mostRecentItemDate?: Date | null
|
||||
|
||||
@Column('text', { nullable: true })
|
||||
lastFetchedChecksum?: string | null
|
||||
|
|
@ -73,6 +83,12 @@ export class Subscription {
|
|||
@Column('timestamp', { nullable: true })
|
||||
scheduledAt?: Date | null
|
||||
|
||||
@Column('timestamp', { nullable: true })
|
||||
refreshedAt?: Date | null
|
||||
|
||||
@Column('timestamp', { nullable: true })
|
||||
failedAt?: Date | null
|
||||
|
||||
@Column('boolean')
|
||||
isPrivate?: boolean | null
|
||||
|
||||
|
|
|
|||
|
|
@ -23,16 +23,17 @@ export class ContentDisplayReportSubscriber
|
|||
${report.user.id} for URL: ${report.originalUrl}
|
||||
${report.reportComment}`
|
||||
|
||||
logger.info(message)
|
||||
|
||||
if (!env.dev.isLocal) {
|
||||
// If we are in the local environment, just log a message, otherwise email the report
|
||||
await sendEmail({
|
||||
to: env.sender.feedback,
|
||||
subject: 'New content display report',
|
||||
text: message,
|
||||
from: env.sender.message,
|
||||
})
|
||||
// If we are in the local environment, just log a message, otherwise email the report
|
||||
if (env.dev.isLocal) {
|
||||
logger.info(message)
|
||||
return
|
||||
}
|
||||
|
||||
await sendEmail({
|
||||
to: env.sender.feedback,
|
||||
subject: 'New content display report',
|
||||
text: message,
|
||||
from: env.sender.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2283,8 +2283,11 @@ export type SaveFileInput = {
|
|||
clientRequestId: Scalars['ID'];
|
||||
folder?: InputMaybe<Scalars['String']>;
|
||||
labels?: InputMaybe<Array<CreateLabelInput>>;
|
||||
publishedAt?: InputMaybe<Scalars['Date']>;
|
||||
savedAt?: InputMaybe<Scalars['Date']>;
|
||||
source: Scalars['String'];
|
||||
state?: InputMaybe<ArticleSavingRequestStatus>;
|
||||
subscription?: InputMaybe<Scalars['String']>;
|
||||
uploadFileId: Scalars['ID'];
|
||||
url: Scalars['String'];
|
||||
};
|
||||
|
|
@ -2833,14 +2836,17 @@ export type Subscription = {
|
|||
count: Scalars['Int'];
|
||||
createdAt: Scalars['Date'];
|
||||
description?: Maybe<Scalars['String']>;
|
||||
failedAt?: Maybe<Scalars['Date']>;
|
||||
fetchContent: Scalars['Boolean'];
|
||||
folder: Scalars['String'];
|
||||
icon?: Maybe<Scalars['String']>;
|
||||
id: Scalars['ID'];
|
||||
isPrivate?: Maybe<Scalars['Boolean']>;
|
||||
lastFetchedAt?: Maybe<Scalars['Date']>;
|
||||
mostRecentItemDate?: Maybe<Scalars['Date']>;
|
||||
name: Scalars['String'];
|
||||
newsletterEmail?: Maybe<Scalars['String']>;
|
||||
refreshedAt?: Maybe<Scalars['Date']>;
|
||||
status: SubscriptionStatus;
|
||||
type: SubscriptionType;
|
||||
unsubscribeHttpUrl?: Maybe<Scalars['String']>;
|
||||
|
|
@ -3205,13 +3211,15 @@ export enum UpdateSubscriptionErrorCode {
|
|||
export type UpdateSubscriptionInput = {
|
||||
autoAddToLibrary?: InputMaybe<Scalars['Boolean']>;
|
||||
description?: InputMaybe<Scalars['String']>;
|
||||
failedAt?: InputMaybe<Scalars['Date']>;
|
||||
fetchContent?: InputMaybe<Scalars['Boolean']>;
|
||||
folder?: InputMaybe<Scalars['String']>;
|
||||
id: Scalars['ID'];
|
||||
isPrivate?: InputMaybe<Scalars['Boolean']>;
|
||||
lastFetchedAt?: InputMaybe<Scalars['Date']>;
|
||||
lastFetchedChecksum?: InputMaybe<Scalars['String']>;
|
||||
mostRecentItemDate?: InputMaybe<Scalars['Date']>;
|
||||
name?: InputMaybe<Scalars['String']>;
|
||||
refreshedAt?: InputMaybe<Scalars['Date']>;
|
||||
scheduledAt?: InputMaybe<Scalars['Date']>;
|
||||
status?: InputMaybe<SubscriptionStatus>;
|
||||
};
|
||||
|
|
@ -6186,14 +6194,17 @@ export type SubscriptionResolvers<ContextType = ResolverContext, ParentType exte
|
|||
count?: SubscriptionResolver<ResolversTypes['Int'], "count", ParentType, ContextType>;
|
||||
createdAt?: SubscriptionResolver<ResolversTypes['Date'], "createdAt", ParentType, ContextType>;
|
||||
description?: SubscriptionResolver<Maybe<ResolversTypes['String']>, "description", ParentType, ContextType>;
|
||||
failedAt?: SubscriptionResolver<Maybe<ResolversTypes['Date']>, "failedAt", ParentType, ContextType>;
|
||||
fetchContent?: SubscriptionResolver<ResolversTypes['Boolean'], "fetchContent", ParentType, ContextType>;
|
||||
folder?: SubscriptionResolver<ResolversTypes['String'], "folder", ParentType, ContextType>;
|
||||
icon?: SubscriptionResolver<Maybe<ResolversTypes['String']>, "icon", ParentType, ContextType>;
|
||||
id?: SubscriptionResolver<ResolversTypes['ID'], "id", ParentType, ContextType>;
|
||||
isPrivate?: SubscriptionResolver<Maybe<ResolversTypes['Boolean']>, "isPrivate", ParentType, ContextType>;
|
||||
lastFetchedAt?: SubscriptionResolver<Maybe<ResolversTypes['Date']>, "lastFetchedAt", ParentType, ContextType>;
|
||||
mostRecentItemDate?: SubscriptionResolver<Maybe<ResolversTypes['Date']>, "mostRecentItemDate", ParentType, ContextType>;
|
||||
name?: SubscriptionResolver<ResolversTypes['String'], "name", ParentType, ContextType>;
|
||||
newsletterEmail?: SubscriptionResolver<Maybe<ResolversTypes['String']>, "newsletterEmail", ParentType, ContextType>;
|
||||
refreshedAt?: SubscriptionResolver<Maybe<ResolversTypes['Date']>, "refreshedAt", ParentType, ContextType>;
|
||||
status?: SubscriptionResolver<ResolversTypes['SubscriptionStatus'], "status", ParentType, ContextType>;
|
||||
type?: SubscriptionResolver<ResolversTypes['SubscriptionType'], "type", ParentType, ContextType>;
|
||||
unsubscribeHttpUrl?: SubscriptionResolver<Maybe<ResolversTypes['String']>, "unsubscribeHttpUrl", ParentType, ContextType>;
|
||||
|
|
|
|||
|
|
@ -1718,8 +1718,11 @@ input SaveFileInput {
|
|||
clientRequestId: ID!
|
||||
folder: String
|
||||
labels: [CreateLabelInput!]
|
||||
publishedAt: Date
|
||||
savedAt: Date
|
||||
source: String!
|
||||
state: ArticleSavingRequestStatus
|
||||
subscription: String
|
||||
uploadFileId: ID!
|
||||
url: String!
|
||||
}
|
||||
|
|
@ -2229,14 +2232,17 @@ type Subscription {
|
|||
count: Int!
|
||||
createdAt: Date!
|
||||
description: String
|
||||
failedAt: Date
|
||||
fetchContent: Boolean!
|
||||
folder: String!
|
||||
icon: String
|
||||
id: ID!
|
||||
isPrivate: Boolean
|
||||
lastFetchedAt: Date
|
||||
mostRecentItemDate: Date
|
||||
name: String!
|
||||
newsletterEmail: String
|
||||
refreshedAt: Date
|
||||
status: SubscriptionStatus!
|
||||
type: SubscriptionType!
|
||||
unsubscribeHttpUrl: String
|
||||
|
|
@ -2572,13 +2578,15 @@ enum UpdateSubscriptionErrorCode {
|
|||
input UpdateSubscriptionInput {
|
||||
autoAddToLibrary: Boolean
|
||||
description: String
|
||||
failedAt: Date
|
||||
fetchContent: Boolean
|
||||
folder: String
|
||||
id: ID!
|
||||
isPrivate: Boolean
|
||||
lastFetchedAt: Date
|
||||
lastFetchedChecksum: String
|
||||
mostRecentItemDate: Date
|
||||
name: String
|
||||
refreshedAt: Date
|
||||
scheduledAt: Date
|
||||
status: SubscriptionStatus
|
||||
}
|
||||
|
|
|
|||
170
packages/api/src/jobs/find_thumbnail.ts
Normal file
170
packages/api/src/jobs/find_thumbnail.ts
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
import axios, { AxiosResponse } from 'axios'
|
||||
import sizeOf from 'image-size'
|
||||
import { parseHTML } from 'linkedom'
|
||||
import {
|
||||
findLibraryItemById,
|
||||
updateLibraryItem,
|
||||
} from '../services/library_item'
|
||||
import { createThumbnailUrl } from '../utils/imageproxy'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
interface Data {
|
||||
libraryItemId: string
|
||||
userId: string
|
||||
}
|
||||
|
||||
interface ImageSize {
|
||||
src: string
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export const THUMBNAIL_JOB = 'find-thumbnail'
|
||||
|
||||
const fetchImage = async (url: string): Promise<AxiosResponse | null> => {
|
||||
logger.info('fetching image', url)
|
||||
try {
|
||||
// get image file by url
|
||||
return await axios.get(url, {
|
||||
responseType: 'arraybuffer',
|
||||
timeout: 10000, // 10s
|
||||
maxContentLength: 20000000, // 20mb
|
||||
})
|
||||
} catch (e) {
|
||||
logger.error('fetch image error', e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const getImageSize = async (src: string): Promise<ImageSize | null> => {
|
||||
try {
|
||||
const response = await fetchImage(src)
|
||||
if (!response) {
|
||||
return null
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
const buffer = Buffer.from(response.data, 'binary')
|
||||
|
||||
// get image size
|
||||
const { width, height } = sizeOf(buffer)
|
||||
|
||||
if (!width || !height) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
src,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error(e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const fetchAllImageSizes = async (content: string) => {
|
||||
const dom = parseHTML(content).document
|
||||
|
||||
// fetch all images by src and get their sizes
|
||||
const images = dom.querySelectorAll('img[src]')
|
||||
if (!images || images.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
return Promise.all(
|
||||
Array.from(images).map((image) => {
|
||||
const src = image.getAttribute('src')
|
||||
if (!src) {
|
||||
return null
|
||||
}
|
||||
|
||||
return getImageSize(src)
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
// credit: https://github.com/reddit-archive/reddit/blob/753b17407e9a9dca09558526805922de24133d53/r2/r2/lib/media.py#L706
|
||||
export const _findThumbnail = (imagesSizes: (ImageSize | null)[]) => {
|
||||
// find the largest and squarest image as the thumbnail
|
||||
let thumbnail = ''
|
||||
let largestArea = 0
|
||||
for (const imageSize of Array.from(imagesSizes)) {
|
||||
if (!imageSize) {
|
||||
continue
|
||||
}
|
||||
|
||||
let area = imageSize.width * imageSize.height
|
||||
|
||||
// ignore small images
|
||||
if (area < 5000) {
|
||||
continue
|
||||
}
|
||||
|
||||
// penalize excessively long/wide images
|
||||
const ratio =
|
||||
Math.max(imageSize.width, imageSize.height) /
|
||||
Math.min(imageSize.width, imageSize.height)
|
||||
if (ratio > 1.5) {
|
||||
area /= ratio * 2
|
||||
}
|
||||
|
||||
// penalize images with "sprite" in their name
|
||||
if (imageSize.src.toLowerCase().includes('sprite')) {
|
||||
area /= 10
|
||||
}
|
||||
|
||||
if (area > largestArea) {
|
||||
largestArea = area
|
||||
thumbnail = imageSize.src
|
||||
}
|
||||
}
|
||||
|
||||
return thumbnail
|
||||
}
|
||||
|
||||
export const findThumbnail = async (data: Data) => {
|
||||
const { libraryItemId, userId } = data
|
||||
|
||||
const item = await findLibraryItemById(libraryItemId, userId)
|
||||
if (!item) {
|
||||
logger.info('page not found')
|
||||
return false
|
||||
}
|
||||
|
||||
const thumbnail = item.thumbnail
|
||||
if (thumbnail) {
|
||||
const proxyUrl = createThumbnailUrl(thumbnail)
|
||||
// pre-cache thumbnail first if exists
|
||||
const image = await fetchImage(proxyUrl)
|
||||
if (!image) {
|
||||
logger.info('thumbnail image not found')
|
||||
item.thumbnail = undefined
|
||||
}
|
||||
}
|
||||
|
||||
logger.info('pre-caching all images...')
|
||||
// pre-cache all images in the content and get their sizes
|
||||
const imageSizes = await fetchAllImageSizes(item.readableContent)
|
||||
// find thumbnail from all images if thumbnail not set
|
||||
if (!item.thumbnail && imageSizes.length > 0) {
|
||||
const thumbnail = _findThumbnail(imageSizes)
|
||||
if (!thumbnail) {
|
||||
logger.info('no thumbnail found from content')
|
||||
return false
|
||||
}
|
||||
|
||||
// update page with thumbnail
|
||||
await updateLibraryItem(
|
||||
libraryItemId,
|
||||
{
|
||||
thumbnail,
|
||||
},
|
||||
userId
|
||||
)
|
||||
logger.info(`thumbnail updated: ${thumbnail}`)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
|
@ -1,11 +1,11 @@
|
|||
import { Job, Queue } from 'bullmq'
|
||||
import { Job } from 'bullmq'
|
||||
import { DataSource } from 'typeorm'
|
||||
import { QUEUE_NAME, getBackendQueue } from '../../queue-processor'
|
||||
import { redisDataSource } from '../../redis_data_source'
|
||||
import { v4 as uuid } from 'uuid'
|
||||
import { getBackendQueue } from '../../queue-processor'
|
||||
import { validateUrl } from '../../services/create_page_save_request'
|
||||
import { RssSubscriptionGroup } from '../../utils/createTask'
|
||||
import { stringToHash } from '../../utils/helpers'
|
||||
import { validateUrl } from '../../services/create_page_save_request'
|
||||
import { v4 as uuid } from 'uuid'
|
||||
import { logger } from '../../utils/logger'
|
||||
|
||||
export type RSSRefreshContext = {
|
||||
type: 'all' | 'user-added'
|
||||
|
|
@ -21,39 +21,44 @@ export const refreshAllFeeds = async (db: DataSource): Promise<boolean> => {
|
|||
} as RSSRefreshContext
|
||||
const subscriptionGroups = (await db.createEntityManager().query(
|
||||
`
|
||||
SELECT
|
||||
url,
|
||||
ARRAY_AGG(id) AS "subscriptionIds",
|
||||
ARRAY_AGG(user_id) AS "userIds",
|
||||
ARRAY_AGG(last_fetched_at) AS "fetchedDates",
|
||||
ARRAY_AGG(coalesce(scheduled_at, NOW())) AS "scheduledDates",
|
||||
ARRAY_AGG(last_fetched_checksum) AS checksums,
|
||||
ARRAY_AGG(fetch_content) AS "fetchContents",
|
||||
ARRAY_AGG(coalesce(folder, $3)) AS folders
|
||||
FROM
|
||||
omnivore.subscriptions
|
||||
WHERE
|
||||
type = $1
|
||||
AND status = $2
|
||||
AND (scheduled_at <= NOW() OR scheduled_at IS NULL)
|
||||
GROUP BY
|
||||
url
|
||||
`,
|
||||
['RSS', 'ACTIVE', 'following']
|
||||
SELECT
|
||||
url,
|
||||
ARRAY_AGG(s.id) AS "subscriptionIds",
|
||||
ARRAY_AGG(s.user_id) AS "userIds",
|
||||
ARRAY_AGG(s.most_recent_item_date) AS "mostRecentItemDates",
|
||||
ARRAY_AGG(coalesce(s.scheduled_at, NOW())) AS "scheduledDates",
|
||||
ARRAY_AGG(s.last_fetched_checksum) AS checksums,
|
||||
ARRAY_AGG(s.fetch_content) AS "fetchContents",
|
||||
ARRAY_AGG(coalesce(s.folder, $3)) AS folders
|
||||
FROM
|
||||
omnivore.subscriptions s
|
||||
INNER JOIN
|
||||
omnivore.user u ON u.id = s.user_id
|
||||
WHERE
|
||||
s.type = $1
|
||||
AND s.status = $2
|
||||
AND (s.scheduled_at <= NOW() OR s.scheduled_at IS NULL)
|
||||
AND u.status = $4
|
||||
GROUP BY
|
||||
s.url
|
||||
`,
|
||||
['RSS', 'ACTIVE', 'following', 'ACTIVE']
|
||||
)) as RssSubscriptionGroup[]
|
||||
|
||||
console.log(`rss: checking ${subscriptionGroups.length}`, { refreshContext })
|
||||
logger.info(`rss: checking ${subscriptionGroups.length}`, {
|
||||
refreshContext,
|
||||
})
|
||||
|
||||
for (const group of subscriptionGroups) {
|
||||
try {
|
||||
await updateSubscriptionGroup(group, refreshContext)
|
||||
} catch (err) {
|
||||
// we don't want to fail the whole job if one subscription group fails
|
||||
console.error('error updating subscription group')
|
||||
logger.error('error updating subscription group')
|
||||
}
|
||||
}
|
||||
const finishTime = new Date()
|
||||
console.log(
|
||||
logger.info(
|
||||
`rss: finished queuing subscription groups at ${finishTime.toISOString()}`,
|
||||
{
|
||||
refreshContext,
|
||||
|
|
@ -70,18 +75,18 @@ const updateSubscriptionGroup = async (
|
|||
let feedURL = group.url
|
||||
const userList = JSON.stringify(group.userIds.sort())
|
||||
if (!feedURL) {
|
||||
console.error('no url for feed group', group)
|
||||
logger.error('no url for feed group', group)
|
||||
return
|
||||
}
|
||||
if (!userList) {
|
||||
console.error('no userlist for feed group', group)
|
||||
logger.error('no userlist for feed group', group)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
feedURL = validateUrl(feedURL).toString()
|
||||
} catch (err) {
|
||||
console.log('not refreshing invalid feed url: ', { feedURL })
|
||||
logger.error(`not refreshing invalid feed url: ${feedURL}`)
|
||||
}
|
||||
const jobid = `refresh-feed_${stringToHash(feedURL)}_${stringToHash(
|
||||
userList
|
||||
|
|
@ -90,7 +95,7 @@ const updateSubscriptionGroup = async (
|
|||
refreshContext,
|
||||
subscriptionIds: group.subscriptionIds,
|
||||
feedUrl: group.url,
|
||||
lastFetchedTimestamps: group.fetchedDates.map(
|
||||
mostRecentItemDates: group.mostRecentItemDates.map(
|
||||
(timestamp) => timestamp?.getTime() || 0
|
||||
), // unix timestamp in milliseconds
|
||||
lastFetchedChecksums: group.checksums,
|
||||
|
|
|
|||
|
|
@ -1,21 +1,24 @@
|
|||
import axios from 'axios'
|
||||
import crypto from 'crypto'
|
||||
import * as jwt from 'jsonwebtoken'
|
||||
import { parseHTML } from 'linkedom'
|
||||
import Parser, { Item } from 'rss-parser'
|
||||
import { promisify } from 'util'
|
||||
import { env } from '../../env'
|
||||
import { redisDataSource } from '../../redis_data_source'
|
||||
import { validateUrl } from '../../services/create_page_save_request'
|
||||
import {
|
||||
updateSubscription,
|
||||
updateSubscriptions,
|
||||
} from '../../services/update_subscription'
|
||||
import createHttpTaskWithToken from '../../utils/createTask'
|
||||
import { logger } from '../../utils/logger'
|
||||
import { RSSRefreshContext } from './refreshAllFeeds'
|
||||
import { updateSubscription } from '../../services/update_subscription'
|
||||
|
||||
type FolderType = 'following' | 'inbox'
|
||||
|
||||
interface RefreshFeedRequest {
|
||||
subscriptionIds: string[]
|
||||
feedUrl: string
|
||||
lastFetchedTimestamps: number[] // unix timestamp in milliseconds
|
||||
mostRecentItemDates: number[] // unix timestamp in milliseconds
|
||||
scheduledTimestamps: number[] // unix timestamp in milliseconds
|
||||
lastFetchedChecksums: string[]
|
||||
userIds: string[]
|
||||
|
|
@ -28,7 +31,7 @@ export const isRefreshFeedRequest = (data: any): data is RefreshFeedRequest => {
|
|||
return (
|
||||
'subscriptionIds' in data &&
|
||||
'feedUrl' in data &&
|
||||
'lastFetchedTimestamps' in data &&
|
||||
'mostRecentItemDates' in data &&
|
||||
'scheduledTimestamps' in data &&
|
||||
'userIds' in data &&
|
||||
'lastFetchedChecksums' in data &&
|
||||
|
|
@ -71,11 +74,14 @@ interface FetchContentTask {
|
|||
item: RssFeedItem
|
||||
}
|
||||
|
||||
export const isOldItem = (item: RssFeedItem, lastFetchedAt: number) => {
|
||||
export const isOldItem = (
|
||||
item: RssFeedItem,
|
||||
mostRecentItemTimestamp: number
|
||||
) => {
|
||||
// existing items and items that were published before 24h
|
||||
const publishedAt = item.isoDate ? new Date(item.isoDate) : new Date()
|
||||
return (
|
||||
publishedAt <= new Date(lastFetchedAt) ||
|
||||
publishedAt <= new Date(mostRecentItemTimestamp) ||
|
||||
publishedAt < new Date(Date.now() - 24 * 60 * 60 * 1000)
|
||||
)
|
||||
}
|
||||
|
|
@ -91,11 +97,11 @@ const isFeedBlocked = async (feedUrl: string) => {
|
|||
// if the feed has failed to fetch more than certain times, block it
|
||||
const maxFailures = parseInt(process.env.MAX_FEED_FETCH_FAILURES ?? '10')
|
||||
if (result && parseInt(result) > maxFailures) {
|
||||
console.log('feed is blocked: ', feedUrl)
|
||||
logger.info(`feed is blocked: ${feedUrl}`)
|
||||
return true
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to check feed block status', feedUrl, error)
|
||||
logger.error('Failed to check feed block status', { feedUrl, error })
|
||||
}
|
||||
|
||||
return false
|
||||
|
|
@ -111,7 +117,7 @@ const incrementFeedFailure = async (feedUrl: string) => {
|
|||
|
||||
return result
|
||||
} catch (error) {
|
||||
console.error('Failed to block feed', feedUrl, error)
|
||||
logger.error('Failed to block feed', { feedUrl, error })
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
|
@ -123,6 +129,9 @@ export const isContentFetchBlocked = (feedUrl: string) => {
|
|||
if (feedUrl.startsWith('https://lwn.net/headlines/newrss')) {
|
||||
return true
|
||||
}
|
||||
if (feedUrl.startsWith('https://medium.com')) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
|
|
@ -156,7 +165,7 @@ export const fetchAndChecksum = async (url: string) => {
|
|||
|
||||
return { url, content: dataStr, checksum: hash.digest('hex') }
|
||||
} catch (error) {
|
||||
console.log(`Failed to fetch or hash content from ${url}.`, error)
|
||||
logger.info(`Failed to fetch or hash content from ${url}.`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
|
@ -200,7 +209,7 @@ const parseFeed = async (url: string, content: string) => {
|
|||
// otherwise the error will be caught by the outer try catch
|
||||
return await parser.parseString(content)
|
||||
} catch (error) {
|
||||
console.log(error)
|
||||
logger.info(error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
|
@ -211,7 +220,7 @@ const isItemRecentlySaved = async (userId: string, url: string) => {
|
|||
const result = await redisDataSource.redisClient?.get(key)
|
||||
return !!result
|
||||
} catch (err) {
|
||||
console.error('error checking if item is old', err)
|
||||
logger.error('error checking if item is old', err)
|
||||
}
|
||||
// If we failed to check, assume the item is good
|
||||
return false
|
||||
|
|
@ -247,7 +256,7 @@ const createTask = async (
|
|||
) => {
|
||||
const isRecentlySaved = await isItemRecentlySaved(userId, item.link)
|
||||
if (isRecentlySaved) {
|
||||
console.log('Item recently saved', item.link)
|
||||
logger.info(`Item recently saved ${item.link}`)
|
||||
return true
|
||||
}
|
||||
|
||||
|
|
@ -255,7 +264,7 @@ const createTask = async (
|
|||
return createItemWithPreviewContent(userId, feedUrl, item)
|
||||
}
|
||||
|
||||
console.log(`adding fetch content task ${userId} ${item.link.trim()}`)
|
||||
logger.info(`adding fetch content task ${userId} ${item.link.trim()}`)
|
||||
return addFetchContentTask(fetchContentTasks, userId, folder, item)
|
||||
}
|
||||
|
||||
|
|
@ -283,7 +292,7 @@ const fetchContentAndCreateItem = async (
|
|||
})
|
||||
return !!task
|
||||
} catch (error) {
|
||||
console.error('Error while creating task', error)
|
||||
logger.error('Error while creating task', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
@ -325,12 +334,11 @@ const createItemWithPreviewContent = async (
|
|||
})
|
||||
return !!task
|
||||
} catch (error) {
|
||||
console.error('Error while creating task', error)
|
||||
logger.error('Error while creating task', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
const signToken = promisify(jwt.sign)
|
||||
const parser = new Parser({
|
||||
customFields: {
|
||||
item: [
|
||||
|
|
@ -388,7 +396,10 @@ const getUpdatePeriodInHours = (feed: RssFeed) => {
|
|||
}
|
||||
|
||||
// get link following the order of preference: via, alternate, self
|
||||
const getLink = (links: RssFeedItemLink[]): string | undefined => {
|
||||
const getLink = (
|
||||
links: RssFeedItemLink[],
|
||||
feedUrl: string
|
||||
): string | undefined => {
|
||||
// sort links by preference
|
||||
const sortedLinks: string[] = []
|
||||
|
||||
|
|
@ -410,7 +421,18 @@ const getLink = (links: RssFeedItemLink[]): string | undefined => {
|
|||
})
|
||||
|
||||
// return the first link that is not undefined
|
||||
return sortedLinks.find((link) => !!link)
|
||||
const itemUrl = sortedLinks.find((link) => !!link)
|
||||
if (!itemUrl) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
// convert relative url to absolute url
|
||||
const url = new URL(itemUrl, feedUrl).href
|
||||
if (!validateUrl(url)) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return url
|
||||
}
|
||||
|
||||
const processSubscription = async (
|
||||
|
|
@ -419,107 +441,120 @@ const processSubscription = async (
|
|||
userId: string,
|
||||
feedUrl: string,
|
||||
fetchResult: { content: string; checksum: string },
|
||||
lastFetchedAt: number,
|
||||
mostRecentItemDate: number,
|
||||
scheduledAt: number,
|
||||
lastFetchedChecksum: string,
|
||||
fetchContent: boolean,
|
||||
folder: FolderType,
|
||||
feed: RssFeed
|
||||
) => {
|
||||
const refreshedAt = new Date()
|
||||
|
||||
let lastItemFetchedAt: Date | null = null
|
||||
let lastValidItem: RssFeedItem | null = null
|
||||
|
||||
if (fetchResult.checksum === lastFetchedChecksum) {
|
||||
console.log('feed has not been updated', feedUrl, lastFetchedChecksum)
|
||||
logger.info('feed has not been updated', { feedUrl, lastFetchedChecksum })
|
||||
return
|
||||
}
|
||||
const updatedLastFetchedChecksum = fetchResult.checksum
|
||||
|
||||
// fetch feed
|
||||
let itemCount = 0
|
||||
let itemCount = 0,
|
||||
failedAt: Date | undefined
|
||||
|
||||
const feedLastBuildDate = feed.lastBuildDate
|
||||
console.log('Feed last build date', feedLastBuildDate)
|
||||
logger.info(`Feed last build date ${feedLastBuildDate || 'N/A'}`)
|
||||
if (
|
||||
feedLastBuildDate &&
|
||||
new Date(feedLastBuildDate) <= new Date(lastFetchedAt)
|
||||
new Date(feedLastBuildDate) <= new Date(mostRecentItemDate)
|
||||
) {
|
||||
console.log('Skipping old feed', feedLastBuildDate)
|
||||
logger.info(`Skipping old feed ${feedLastBuildDate}`)
|
||||
return
|
||||
}
|
||||
|
||||
// save each item in the feed
|
||||
for (const item of feed.items) {
|
||||
// use published or updated if isoDate is not available for atom feeds
|
||||
const isoDate =
|
||||
item.isoDate || item.published || item.updated || item.created
|
||||
console.log('Processing feed item', item.links, item.isoDate, feedUrl)
|
||||
try {
|
||||
const guid = item.guid || item.link
|
||||
// use published or updated if isoDate is not available for atom feeds
|
||||
const isoDate =
|
||||
item.isoDate || item.published || item.updated || item.created
|
||||
|
||||
if (!item.links || item.links.length === 0) {
|
||||
console.log('Invalid feed item', item)
|
||||
continue
|
||||
logger.info('Processing feed item', {
|
||||
guid,
|
||||
links: item.links,
|
||||
isoDate,
|
||||
feedUrl,
|
||||
})
|
||||
|
||||
if (!item.links || item.links.length === 0 || !guid) {
|
||||
throw new Error('Invalid feed item')
|
||||
}
|
||||
|
||||
// fallback to guid if link is not available
|
||||
const link = getLink(item.links, feedUrl) || guid
|
||||
if (!link) {
|
||||
throw new Error('Invalid feed item link')
|
||||
}
|
||||
|
||||
const feedItem = {
|
||||
...item,
|
||||
isoDate,
|
||||
link,
|
||||
}
|
||||
|
||||
const publishedAt = feedItem.isoDate
|
||||
? new Date(feedItem.isoDate)
|
||||
: new Date()
|
||||
// remember the last valid item
|
||||
if (
|
||||
!lastValidItem ||
|
||||
(lastValidItem.isoDate && publishedAt > new Date(lastValidItem.isoDate))
|
||||
) {
|
||||
lastValidItem = feedItem
|
||||
}
|
||||
|
||||
// Max limit per-feed update
|
||||
if (itemCount > 99) {
|
||||
continue
|
||||
}
|
||||
|
||||
// skip old items
|
||||
if (isOldItem(feedItem, mostRecentItemDate)) {
|
||||
logger.info(`Skipping old feed item ${feedItem.link}`)
|
||||
continue
|
||||
}
|
||||
|
||||
const created = await createTask(
|
||||
fetchContentTasks,
|
||||
userId,
|
||||
feedUrl,
|
||||
feedItem,
|
||||
fetchContent,
|
||||
folder
|
||||
)
|
||||
if (!created) {
|
||||
throw new Error('Failed to create task for feed item')
|
||||
}
|
||||
|
||||
// remember the last item fetched at
|
||||
if (!lastItemFetchedAt || publishedAt > lastItemFetchedAt) {
|
||||
lastItemFetchedAt = publishedAt
|
||||
}
|
||||
|
||||
itemCount = itemCount + 1
|
||||
} catch (error) {
|
||||
logger.error('Error while saving RSS feed item', { error, item })
|
||||
failedAt = new Date()
|
||||
}
|
||||
|
||||
const link = getLink(item.links)
|
||||
if (!link) {
|
||||
console.log('Invalid feed item links', item.links)
|
||||
continue
|
||||
}
|
||||
|
||||
const feedItem = {
|
||||
...item,
|
||||
isoDate,
|
||||
link,
|
||||
}
|
||||
|
||||
const publishedAt = feedItem.isoDate
|
||||
? new Date(feedItem.isoDate)
|
||||
: new Date()
|
||||
// remember the last valid item
|
||||
if (
|
||||
!lastValidItem ||
|
||||
(lastValidItem.isoDate && publishedAt > new Date(lastValidItem.isoDate))
|
||||
) {
|
||||
lastValidItem = feedItem
|
||||
}
|
||||
|
||||
// Max limit per-feed update
|
||||
if (itemCount > 99) {
|
||||
continue
|
||||
}
|
||||
|
||||
// skip old items
|
||||
if (isOldItem(feedItem, lastFetchedAt)) {
|
||||
console.log('Skipping old feed item', feedItem.link)
|
||||
continue
|
||||
}
|
||||
|
||||
const created = await createTask(
|
||||
fetchContentTasks,
|
||||
userId,
|
||||
feedUrl,
|
||||
feedItem,
|
||||
fetchContent,
|
||||
folder
|
||||
)
|
||||
if (!created) {
|
||||
console.error('Failed to create task for feed item', feedItem.link)
|
||||
continue
|
||||
}
|
||||
|
||||
// remember the last item fetched at
|
||||
if (!lastItemFetchedAt || publishedAt > lastItemFetchedAt) {
|
||||
lastItemFetchedAt = publishedAt
|
||||
}
|
||||
|
||||
itemCount = itemCount + 1
|
||||
}
|
||||
|
||||
// no items saved
|
||||
if (!lastItemFetchedAt) {
|
||||
if (!lastItemFetchedAt && !failedAt) {
|
||||
// the feed has been fetched before, no new valid items found
|
||||
if (lastFetchedAt || !lastValidItem) {
|
||||
console.log('No new valid items found')
|
||||
if (mostRecentItemDate || !lastValidItem) {
|
||||
logger.info('No new valid items found')
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -533,95 +568,109 @@ const processSubscription = async (
|
|||
folder
|
||||
)
|
||||
if (!created) {
|
||||
console.error('Failed to create task for feed item', lastValidItem.link)
|
||||
throw new Error('Failed to create task for feed item')
|
||||
logger.error('Failed to create task for feed item', {
|
||||
url: lastValidItem.link,
|
||||
})
|
||||
failedAt = new Date()
|
||||
}
|
||||
|
||||
lastItemFetchedAt = lastValidItem.isoDate
|
||||
? new Date(lastValidItem.isoDate)
|
||||
: new Date()
|
||||
: refreshedAt
|
||||
}
|
||||
|
||||
const updateFrequency = getUpdateFrequency(feed)
|
||||
const updatePeriodInMs = getUpdatePeriodInHours(feed) * 60 * 60 * 1000
|
||||
const nextScheduledAt = scheduledAt + updatePeriodInMs * updateFrequency
|
||||
|
||||
// update subscription lastFetchedAt
|
||||
// update subscription mostRecentItemDate and refreshedAt
|
||||
const updatedSubscription = await updateSubscription(userId, subscriptionId, {
|
||||
lastFetchedAt: lastItemFetchedAt,
|
||||
mostRecentItemDate: lastItemFetchedAt,
|
||||
lastFetchedChecksum: updatedLastFetchedChecksum,
|
||||
scheduledAt: new Date(nextScheduledAt),
|
||||
refreshedAt,
|
||||
failedAt,
|
||||
})
|
||||
console.log('Updated subscription', updatedSubscription)
|
||||
logger.info('Updated subscription', updatedSubscription)
|
||||
}
|
||||
|
||||
export const refreshFeed = async (request: any) => {
|
||||
if (isRefreshFeedRequest(request)) {
|
||||
return _refreshFeed(request)
|
||||
}
|
||||
console.log('not a feed to refresh')
|
||||
logger.info('not a feed to refresh')
|
||||
return false
|
||||
}
|
||||
|
||||
export const _refreshFeed = async (request: RefreshFeedRequest) => {
|
||||
try {
|
||||
const {
|
||||
feedUrl,
|
||||
subscriptionIds,
|
||||
lastFetchedTimestamps,
|
||||
scheduledTimestamps,
|
||||
userIds,
|
||||
lastFetchedChecksums,
|
||||
fetchContents,
|
||||
folders,
|
||||
refreshContext,
|
||||
} = request
|
||||
console.log('Processing feed', feedUrl, { refreshContext: refreshContext })
|
||||
const {
|
||||
feedUrl,
|
||||
subscriptionIds,
|
||||
mostRecentItemDates,
|
||||
scheduledTimestamps,
|
||||
userIds,
|
||||
lastFetchedChecksums,
|
||||
fetchContents,
|
||||
folders,
|
||||
refreshContext,
|
||||
} = request
|
||||
|
||||
logger.info('Processing feed', feedUrl, { refreshContext: refreshContext })
|
||||
|
||||
try {
|
||||
const isBlocked = await isFeedBlocked(feedUrl)
|
||||
if (isBlocked) {
|
||||
console.log('feed is blocked: ', feedUrl)
|
||||
return
|
||||
logger.info(`feed is blocked: ${feedUrl}`)
|
||||
throw new Error('feed is blocked')
|
||||
}
|
||||
|
||||
const fetchResult = await fetchAndChecksum(feedUrl)
|
||||
if (!fetchResult) {
|
||||
console.error('Failed to fetch RSS feed', feedUrl)
|
||||
logger.error(`Failed to fetch RSS feed ${feedUrl}`)
|
||||
await incrementFeedFailure(feedUrl)
|
||||
return
|
||||
throw new Error('Failed to fetch RSS feed')
|
||||
}
|
||||
|
||||
const feed = await parseFeed(feedUrl, fetchResult.content)
|
||||
if (!feed) {
|
||||
console.error('Failed to parse RSS feed', feedUrl)
|
||||
logger.error(`Failed to parse RSS feed ${feedUrl}`)
|
||||
await incrementFeedFailure(feedUrl)
|
||||
return
|
||||
throw new Error('Failed to parse RSS feed')
|
||||
}
|
||||
|
||||
let allowFetchContent = true
|
||||
if (isContentFetchBlocked(feedUrl)) {
|
||||
console.log('fetching content blocked for feed: ', feedUrl)
|
||||
logger.info(`fetching content blocked for feed: ${feedUrl}`)
|
||||
allowFetchContent = false
|
||||
}
|
||||
|
||||
console.log('Fetched feed', feed.title, new Date())
|
||||
logger.info('Fetched feed', { title: feed.title, at: new Date() })
|
||||
|
||||
const fetchContentTasks = new Map<string, FetchContentTask>() // url -> FetchContentTask
|
||||
// process each subscription sequentially
|
||||
for (let i = 0; i < subscriptionIds.length; i++) {
|
||||
await processSubscription(
|
||||
fetchContentTasks,
|
||||
subscriptionIds[i],
|
||||
userIds[i],
|
||||
feedUrl,
|
||||
fetchResult,
|
||||
lastFetchedTimestamps[i],
|
||||
scheduledTimestamps[i],
|
||||
lastFetchedChecksums[i],
|
||||
fetchContents[i] && allowFetchContent,
|
||||
folders[i],
|
||||
feed
|
||||
)
|
||||
const subscriptionId = subscriptionIds[i]
|
||||
|
||||
try {
|
||||
await processSubscription(
|
||||
fetchContentTasks,
|
||||
subscriptionId,
|
||||
userIds[i],
|
||||
feedUrl,
|
||||
fetchResult,
|
||||
mostRecentItemDates[i],
|
||||
scheduledTimestamps[i],
|
||||
lastFetchedChecksums[i],
|
||||
fetchContents[i] && allowFetchContent,
|
||||
folders[i],
|
||||
feed
|
||||
)
|
||||
} catch (error) {
|
||||
logger.error('Error while processing subscription', {
|
||||
error,
|
||||
subscriptionId,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// create fetch content tasks
|
||||
|
|
@ -632,7 +681,22 @@ export const _refreshFeed = async (request: RefreshFeedRequest) => {
|
|||
task.item
|
||||
)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error while saving RSS feeds', e)
|
||||
|
||||
return true
|
||||
} catch (error) {
|
||||
logger.error('Error while saving RSS feeds', {
|
||||
feedUrl,
|
||||
subscriptionIds,
|
||||
error,
|
||||
})
|
||||
|
||||
const now = new Date()
|
||||
// mark subscriptions as error if we failed to get the feed
|
||||
await updateSubscriptions(subscriptionIds, {
|
||||
refreshedAt: now,
|
||||
failedAt: now,
|
||||
})
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import { Readability } from '@omnivore/readability'
|
||||
import axios from 'axios'
|
||||
import jwt from 'jsonwebtoken'
|
||||
import { promisify } from 'util'
|
||||
|
|
@ -9,14 +8,15 @@ import {
|
|||
} from '../generated/graphql'
|
||||
import { redisDataSource } from '../redis_data_source'
|
||||
import { userRepository } from '../repository/user'
|
||||
import { saveFile } from '../services/save_file'
|
||||
import { savePage } from '../services/save_page'
|
||||
import { uploadFile } from '../services/upload_file'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
const signToken = promisify(jwt.sign)
|
||||
|
||||
const IMPORTER_METRICS_COLLECTOR_URL = env.queue.importerMetricsUrl
|
||||
const JWT_SECRET = env.server.jwtSecret
|
||||
const REST_BACKEND_ENDPOINT = `${env.server.internalApiUrl}/api`
|
||||
|
||||
const MAX_ATTEMPTS = 2
|
||||
const REQUEST_TIMEOUT = 30000 // 30 seconds
|
||||
|
|
@ -35,54 +35,15 @@ interface Data {
|
|||
taskId?: string
|
||||
}
|
||||
|
||||
interface UploadFileResponse {
|
||||
data: {
|
||||
uploadFileRequest: {
|
||||
id: string
|
||||
uploadSignedUrl: string
|
||||
uploadFileId: string
|
||||
createdPageId: string
|
||||
errorCodes?: string[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface CreateArticleResponse {
|
||||
data: {
|
||||
createArticle: {
|
||||
createdArticle: {
|
||||
id: string
|
||||
}
|
||||
errorCodes: string[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface SavePageResponse {
|
||||
data: {
|
||||
savePage: {
|
||||
url: string
|
||||
clientRequestId: string
|
||||
errorCodes?: string[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface FetchResult {
|
||||
finalUrl: string
|
||||
title?: string
|
||||
content?: string
|
||||
contentType?: string
|
||||
readabilityResult?: Readability.ParseResult
|
||||
}
|
||||
|
||||
const isFetchResult = (obj: unknown): obj is FetchResult => {
|
||||
return (
|
||||
typeof obj === 'object' &&
|
||||
obj !== null &&
|
||||
'finalUrl' in obj &&
|
||||
'title' in obj
|
||||
)
|
||||
return typeof obj === 'object' && obj !== null && 'finalUrl' in obj
|
||||
}
|
||||
|
||||
const uploadToSignedUrl = async (
|
||||
|
|
@ -90,12 +51,18 @@ const uploadToSignedUrl = async (
|
|||
contentType: string,
|
||||
contentObjUrl: string
|
||||
) => {
|
||||
logger.info('uploading to signed url', {
|
||||
uploadSignedUrl,
|
||||
contentType,
|
||||
contentObjUrl,
|
||||
})
|
||||
|
||||
try {
|
||||
const stream = await axios.get(contentObjUrl, {
|
||||
responseType: 'stream',
|
||||
timeout: REQUEST_TIMEOUT,
|
||||
})
|
||||
return axios.put(uploadSignedUrl, stream.data, {
|
||||
return await axios.put(uploadSignedUrl, stream.data, {
|
||||
headers: {
|
||||
'Content-Type': contentType,
|
||||
},
|
||||
|
|
@ -104,65 +71,7 @@ const uploadToSignedUrl = async (
|
|||
timeout: REQUEST_TIMEOUT,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('error uploading to signed url', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const getUploadIdAndSignedUrl = async (
|
||||
userId: string,
|
||||
url: string,
|
||||
articleSavingRequestId: string
|
||||
) => {
|
||||
const auth = await signToken({ uid: userId }, JWT_SECRET)
|
||||
const data = JSON.stringify({
|
||||
query: `mutation UploadFileRequest($input: UploadFileRequestInput!) {
|
||||
uploadFileRequest(input:$input) {
|
||||
... on UploadFileRequestError {
|
||||
errorCodes
|
||||
}
|
||||
... on UploadFileRequestSuccess {
|
||||
id
|
||||
uploadSignedUrl
|
||||
}
|
||||
}
|
||||
}`,
|
||||
variables: {
|
||||
input: {
|
||||
url,
|
||||
contentType: 'application/pdf',
|
||||
clientRequestId: articleSavingRequestId,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
const response = await axios.post<UploadFileResponse>(
|
||||
`${REST_BACKEND_ENDPOINT}/graphql`,
|
||||
data,
|
||||
{
|
||||
headers: {
|
||||
Cookie: `auth=${auth as string};`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT,
|
||||
}
|
||||
)
|
||||
|
||||
if (
|
||||
response.data.data.uploadFileRequest.errorCodes &&
|
||||
response.data.data.uploadFileRequest.errorCodes?.length > 0
|
||||
) {
|
||||
console.error(
|
||||
'Error while getting upload id and signed url',
|
||||
response.data.data.uploadFileRequest.errorCodes[0]
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
return response.data.data.uploadFileRequest
|
||||
} catch (e) {
|
||||
console.error('error getting upload id and signed url', e)
|
||||
logger.error('error uploading to signed url', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
|
@ -172,73 +81,31 @@ const uploadPdf = async (
|
|||
userId: string,
|
||||
articleSavingRequestId: string
|
||||
) => {
|
||||
const uploadResult = await getUploadIdAndSignedUrl(
|
||||
userId,
|
||||
url,
|
||||
articleSavingRequestId
|
||||
const result = await uploadFile(
|
||||
{
|
||||
url,
|
||||
contentType: 'application/pdf',
|
||||
clientRequestId: articleSavingRequestId,
|
||||
createPageEntry: true,
|
||||
},
|
||||
userId
|
||||
)
|
||||
if (!uploadResult) {
|
||||
if (!result.uploadSignedUrl || !result.createdPageId) {
|
||||
throw new Error('error while getting upload id and signed url')
|
||||
}
|
||||
|
||||
const uploaded = await uploadToSignedUrl(
|
||||
uploadResult.uploadSignedUrl,
|
||||
result.uploadSignedUrl,
|
||||
'application/pdf',
|
||||
url
|
||||
)
|
||||
if (!uploaded) {
|
||||
throw new Error('error while uploading pdf')
|
||||
}
|
||||
return uploadResult.id
|
||||
}
|
||||
|
||||
const sendCreateArticleMutation = async (userId: string, input: unknown) => {
|
||||
const data = JSON.stringify({
|
||||
query: `mutation CreateArticle ($input: CreateArticleInput!){
|
||||
createArticle(input:$input){
|
||||
... on CreateArticleSuccess{
|
||||
createdArticle{
|
||||
id
|
||||
}
|
||||
}
|
||||
... on CreateArticleError{
|
||||
errorCodes
|
||||
}
|
||||
}
|
||||
}`,
|
||||
variables: {
|
||||
input,
|
||||
},
|
||||
})
|
||||
|
||||
const auth = await signToken({ uid: userId }, JWT_SECRET)
|
||||
try {
|
||||
const response = await axios.post<CreateArticleResponse>(
|
||||
`${REST_BACKEND_ENDPOINT}/graphql`,
|
||||
data,
|
||||
{
|
||||
headers: {
|
||||
Cookie: `auth=${auth as string};`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
timeout: REQUEST_TIMEOUT,
|
||||
}
|
||||
)
|
||||
|
||||
if (
|
||||
response.data.data.createArticle.errorCodes &&
|
||||
response.data.data.createArticle.errorCodes.length > 0
|
||||
) {
|
||||
console.error(
|
||||
'error while creating article',
|
||||
response.data.data.createArticle.errorCodes[0]
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
return response.data.data.createArticle
|
||||
} catch (error) {
|
||||
console.error('error creating article', error)
|
||||
return null
|
||||
return {
|
||||
uploadFileId: result.id,
|
||||
itemId: result.createdPageId,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -248,6 +115,7 @@ const sendImportStatusUpdate = async (
|
|||
isImported?: boolean
|
||||
) => {
|
||||
try {
|
||||
logger.info('sending import status update')
|
||||
const auth = await signToken({ uid: userId }, JWT_SECRET)
|
||||
|
||||
await axios.post(
|
||||
|
|
@ -265,7 +133,7 @@ const sendImportStatusUpdate = async (
|
|||
}
|
||||
)
|
||||
} catch (e) {
|
||||
console.error('error while sending import status update', e)
|
||||
logger.error('error while sending import status update', e)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -285,7 +153,7 @@ const getCachedFetchResult = async (url: string) => {
|
|||
throw new Error('fetch result is not valid')
|
||||
}
|
||||
|
||||
console.log('fetch result is cached', url)
|
||||
logger.info('fetch result is cached', url)
|
||||
|
||||
return fetchResult
|
||||
}
|
||||
|
|
@ -294,7 +162,6 @@ export const savePageJob = async (data: Data, attemptsMade: number) => {
|
|||
const {
|
||||
userId,
|
||||
articleSavingRequestId,
|
||||
state,
|
||||
labels,
|
||||
source,
|
||||
folder,
|
||||
|
|
@ -304,38 +171,49 @@ export const savePageJob = async (data: Data, attemptsMade: number) => {
|
|||
taskId,
|
||||
url,
|
||||
} = data
|
||||
let isImported, isSaved
|
||||
let isImported,
|
||||
isSaved,
|
||||
state = data.state
|
||||
|
||||
try {
|
||||
console.log(`savePageJob: ${userId} ${url}`)
|
||||
logger.info(`savePageJob: ${userId} ${url}`)
|
||||
|
||||
// get the fetch result from cache
|
||||
const { title, content, contentType, readabilityResult } =
|
||||
await getCachedFetchResult(url)
|
||||
const fetchedResult = await getCachedFetchResult(url)
|
||||
const { title, contentType } = fetchedResult
|
||||
let content = fetchedResult.content
|
||||
|
||||
const user = await userRepository.findById(userId)
|
||||
if (!user) {
|
||||
logger.error('Unable to save job, user can not be found.', {
|
||||
userId,
|
||||
url,
|
||||
})
|
||||
// if the user is not found, we do not retry
|
||||
return false
|
||||
}
|
||||
|
||||
// for pdf content, we need to upload the pdf
|
||||
if (contentType === 'application/pdf') {
|
||||
const encodedUrl = encodeURI(url)
|
||||
const uploadResult = await uploadPdf(url, userId, articleSavingRequestId)
|
||||
|
||||
const uploadFileId = await uploadPdf(
|
||||
encodedUrl,
|
||||
userId,
|
||||
articleSavingRequestId
|
||||
const result = await saveFile(
|
||||
{
|
||||
url,
|
||||
uploadFileId: uploadResult.uploadFileId,
|
||||
state: state ? (state as ArticleSavingRequestStatus) : undefined,
|
||||
labels,
|
||||
source,
|
||||
folder,
|
||||
subscription: rssFeedUrl,
|
||||
savedAt,
|
||||
publishedAt,
|
||||
clientRequestId: uploadResult.itemId,
|
||||
},
|
||||
user
|
||||
)
|
||||
const uploadedPdf = await sendCreateArticleMutation(userId, {
|
||||
url: encodedUrl,
|
||||
articleSavingRequestId,
|
||||
uploadFileId,
|
||||
state,
|
||||
labels,
|
||||
source,
|
||||
folder,
|
||||
rssFeedUrl,
|
||||
savedAt,
|
||||
publishedAt,
|
||||
})
|
||||
if (!uploadedPdf) {
|
||||
throw new Error('error while saving uploaded pdf')
|
||||
if (result.__typename == 'SaveError') {
|
||||
throw new Error(result.message || result.errorCodes[0])
|
||||
}
|
||||
|
||||
isSaved = true
|
||||
|
|
@ -344,18 +222,10 @@ export const savePageJob = async (data: Data, attemptsMade: number) => {
|
|||
}
|
||||
|
||||
if (!content) {
|
||||
throw new Error(
|
||||
'Invalid SavePage job, fetch result missing required data'
|
||||
)
|
||||
}
|
||||
|
||||
const user = await userRepository.findById(userId)
|
||||
if (!user) {
|
||||
logger.error('Unable to save job, user can not be found.', {
|
||||
userId,
|
||||
url,
|
||||
})
|
||||
throw new Error('Unable to save job, user can not be found.')
|
||||
logger.info('content is not fetched', url)
|
||||
// set the state to failed if we don't have content
|
||||
content = 'Failed to fetch content'
|
||||
state = ArticleSavingRequestStatus.Failed
|
||||
}
|
||||
|
||||
// for non-pdf content, we need to save the page
|
||||
|
|
@ -365,7 +235,6 @@ export const savePageJob = async (data: Data, attemptsMade: number) => {
|
|||
clientRequestId: articleSavingRequestId,
|
||||
title,
|
||||
originalContent: content,
|
||||
parseResult: readabilityResult,
|
||||
state: state ? (state as ArticleSavingRequestStatus) : undefined,
|
||||
labels: labels,
|
||||
rssFeedUrl,
|
||||
|
|
@ -377,26 +246,24 @@ export const savePageJob = async (data: Data, attemptsMade: number) => {
|
|||
user
|
||||
)
|
||||
|
||||
// if (result.__typename == 'SaveError') {
|
||||
// logger.error('Error saving page', { userId, url, result })
|
||||
// throw new Error('Error saving page')
|
||||
// }
|
||||
if (result.__typename == 'SaveError') {
|
||||
throw new Error(result.message || result.errorCodes[0])
|
||||
}
|
||||
|
||||
// if the readability result is not parsed, the import is failed
|
||||
isImported = !!readabilityResult
|
||||
isImported = true
|
||||
isSaved = true
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
console.error('error while saving page', e.message)
|
||||
logger.error(`error while saving page: ${e.message}`)
|
||||
} else {
|
||||
console.error('error while saving page', 'unknown error')
|
||||
logger.error('error while saving page: unknown error')
|
||||
}
|
||||
|
||||
throw e
|
||||
} finally {
|
||||
const lastAttempt = attemptsMade === MAX_ATTEMPTS - 1
|
||||
if (lastAttempt) {
|
||||
console.log('last attempt reached', data.url)
|
||||
logger.info(`last attempt reached ${data.url}`)
|
||||
}
|
||||
|
||||
if (taskId && (isSaved || lastAttempt)) {
|
||||
|
|
|
|||
144
packages/api/src/jobs/trigger_rule.ts
Normal file
144
packages/api/src/jobs/trigger_rule.ts
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
import { LibraryItem, LibraryItemState } from '../entity/library_item'
|
||||
import { Rule, RuleAction, RuleActionType, RuleEventType } from '../entity/rule'
|
||||
import { addLabelsToLibraryItem } from '../services/labels'
|
||||
import {
|
||||
SearchArgs,
|
||||
searchLibraryItems,
|
||||
updateLibraryItem,
|
||||
} from '../services/library_item'
|
||||
import { findEnabledRules } from '../services/rules'
|
||||
import { sendPushNotifications } from '../services/user'
|
||||
import { logger } from '../utils/logger'
|
||||
|
||||
export interface TriggerRuleJobData {
|
||||
libraryItemId: string
|
||||
userId: string
|
||||
ruleEventType: RuleEventType
|
||||
}
|
||||
|
||||
interface RuleActionObj {
|
||||
userId: string
|
||||
action: RuleAction
|
||||
libraryItem: LibraryItem
|
||||
}
|
||||
|
||||
export const TRIGGER_RULE_JOB_NAME = 'trigger-rule'
|
||||
|
||||
type RuleActionFunc = (obj: RuleActionObj) => Promise<unknown>
|
||||
|
||||
const addLabels = async (obj: RuleActionObj) => {
|
||||
const labelIds = obj.action.params
|
||||
|
||||
return addLabelsToLibraryItem(
|
||||
labelIds,
|
||||
obj.libraryItem.id,
|
||||
obj.userId,
|
||||
'system'
|
||||
)
|
||||
}
|
||||
|
||||
const archivePage = async (obj: RuleActionObj) => {
|
||||
return updateLibraryItem(
|
||||
obj.libraryItem.id,
|
||||
{ archivedAt: new Date(), state: LibraryItemState.Archived },
|
||||
obj.userId,
|
||||
undefined,
|
||||
true
|
||||
)
|
||||
}
|
||||
|
||||
const markPageAsRead = async (obj: RuleActionObj) => {
|
||||
return updateLibraryItem(
|
||||
obj.libraryItem.id,
|
||||
{
|
||||
readingProgressTopPercent: 100,
|
||||
readingProgressBottomPercent: 100,
|
||||
readAt: new Date(),
|
||||
},
|
||||
obj.userId,
|
||||
undefined,
|
||||
true
|
||||
)
|
||||
}
|
||||
|
||||
const sendNotification = async (obj: RuleActionObj) => {
|
||||
const item = obj.libraryItem
|
||||
const message = {
|
||||
title: item.author || item.siteName || 'Omnivore',
|
||||
body: item.title,
|
||||
}
|
||||
|
||||
return sendPushNotifications(obj.userId, message, 'rule')
|
||||
}
|
||||
|
||||
const getRuleAction = (actionType: RuleActionType): RuleActionFunc => {
|
||||
switch (actionType) {
|
||||
case RuleActionType.AddLabel:
|
||||
return addLabels
|
||||
case RuleActionType.Archive:
|
||||
return archivePage
|
||||
case RuleActionType.MarkAsRead:
|
||||
return markPageAsRead
|
||||
case RuleActionType.SendNotification:
|
||||
return sendNotification
|
||||
}
|
||||
}
|
||||
|
||||
const triggerActions = async (
|
||||
userId: string,
|
||||
rules: Rule[],
|
||||
data: TriggerRuleJobData
|
||||
) => {
|
||||
const actionPromises: Promise<unknown>[] = []
|
||||
|
||||
for (const rule of rules) {
|
||||
const itemId = data.libraryItemId
|
||||
const searchArgs: SearchArgs = {
|
||||
includeContent: false,
|
||||
includeDeleted: false,
|
||||
includePending: false,
|
||||
size: 1,
|
||||
query: `(${rule.filter}) AND includes:${itemId}`,
|
||||
}
|
||||
|
||||
const libraryItems = await searchLibraryItems(searchArgs, userId)
|
||||
if (libraryItems.count === 0) {
|
||||
logger.info(`No pages found for rule ${rule.id}`)
|
||||
continue
|
||||
}
|
||||
|
||||
const libraryItem = libraryItems.libraryItems[0]
|
||||
|
||||
for (const action of rule.actions) {
|
||||
const actionFunc = getRuleAction(action.type)
|
||||
const actionObj: RuleActionObj = {
|
||||
userId,
|
||||
action,
|
||||
libraryItem,
|
||||
}
|
||||
|
||||
actionPromises.push(actionFunc(actionObj))
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await Promise.all(actionPromises)
|
||||
} catch (error) {
|
||||
logger.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
export const triggerRule = async (data: TriggerRuleJobData) => {
|
||||
const { userId, ruleEventType } = data
|
||||
|
||||
// get rules by calling api
|
||||
const rules = await findEnabledRules(userId, ruleEventType)
|
||||
if (rules.length === 0) {
|
||||
console.log('No rules found')
|
||||
return false
|
||||
}
|
||||
|
||||
await triggerActions(userId, rules, data)
|
||||
|
||||
return true
|
||||
}
|
||||
|
|
@ -1,5 +1,4 @@
|
|||
import {
|
||||
UpdateContentMessage,
|
||||
isUpdateContentMessage,
|
||||
updateContentForFileItem,
|
||||
} from '../services/update_pdf_content'
|
||||
|
|
@ -9,6 +8,6 @@ export const updatePDFContentJob = async (data: unknown): Promise<boolean> => {
|
|||
if (isUpdateContentMessage(data)) {
|
||||
return await updateContentForFileItem(data)
|
||||
}
|
||||
logger.log('update_pdf_content data is not a update message', { data })
|
||||
logger.info('update_pdf_content data is not a update message', { data })
|
||||
return false
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { PubSub } from '@google-cloud/pubsub'
|
||||
import express from 'express'
|
||||
import { RuleEventType } from './entity/rule'
|
||||
import { env } from './env'
|
||||
import { ReportType } from './generated/graphql'
|
||||
import { enqueueTriggerRuleJob } from './utils/createTask'
|
||||
import { deepDelete } from './utils/helpers'
|
||||
import { buildLogger } from './utils/logger'
|
||||
|
||||
|
|
@ -41,11 +43,21 @@ export const createPubSubClient = (): PubsubClient => {
|
|||
Buffer.from(JSON.stringify({ userId, email, name, username }))
|
||||
)
|
||||
},
|
||||
entityCreated: <T>(
|
||||
entityCreated: async <T>(
|
||||
type: EntityType,
|
||||
data: T,
|
||||
userId: string
|
||||
): Promise<void> => {
|
||||
// queue trigger rule job
|
||||
if (type === EntityType.PAGE) {
|
||||
const libraryItemId = (data as T & { id: string }).id
|
||||
await enqueueTriggerRuleJob({
|
||||
userId,
|
||||
ruleEventType: RuleEventType.PageCreated,
|
||||
libraryItemId,
|
||||
})
|
||||
}
|
||||
|
||||
const cleanData = deepDelete(
|
||||
data as T & Record<typeof fieldsToDelete[number], unknown>,
|
||||
[...fieldsToDelete]
|
||||
|
|
@ -56,11 +68,21 @@ export const createPubSubClient = (): PubsubClient => {
|
|||
Buffer.from(JSON.stringify({ type, userId, ...cleanData }))
|
||||
)
|
||||
},
|
||||
entityUpdated: <T>(
|
||||
entityUpdated: async <T>(
|
||||
type: EntityType,
|
||||
data: T,
|
||||
userId: string
|
||||
): Promise<void> => {
|
||||
// queue trigger rule job
|
||||
if (type === EntityType.PAGE) {
|
||||
const libraryItemId = (data as T & { id: string }).id
|
||||
await enqueueTriggerRuleJob({
|
||||
userId,
|
||||
ruleEventType: RuleEventType.PageUpdated,
|
||||
libraryItemId,
|
||||
})
|
||||
}
|
||||
|
||||
const cleanData = deepDelete(
|
||||
data as T & Record<typeof fieldsToDelete[number], unknown>,
|
||||
[...fieldsToDelete]
|
||||
|
|
|
|||
|
|
@ -2,17 +2,19 @@
|
|||
/* eslint-disable @typescript-eslint/restrict-template-expressions */
|
||||
/* eslint-disable @typescript-eslint/require-await */
|
||||
/* eslint-disable @typescript-eslint/no-misused-promises */
|
||||
import { Job, QueueEvents, Worker, Queue } from 'bullmq'
|
||||
import { Job, Queue, QueueEvents, Worker, JobType } from 'bullmq'
|
||||
import express, { Express } from 'express'
|
||||
import { SnakeNamingStrategy } from 'typeorm-naming-strategies'
|
||||
import { appDataSource } from './data_source'
|
||||
import { env } from './env'
|
||||
import { findThumbnail, THUMBNAIL_JOB } from './jobs/find_thumbnail'
|
||||
import { refreshAllFeeds } from './jobs/rss/refreshAllFeeds'
|
||||
import { refreshFeed } from './jobs/rss/refreshFeed'
|
||||
import { savePageJob } from './jobs/save_page'
|
||||
import { updatePDFContentJob } from './jobs/update_pdf_content'
|
||||
import { redisDataSource } from './redis_data_source'
|
||||
import { CustomTypeOrmLogger } from './utils/logger'
|
||||
import { updatePDFContentJob } from './jobs/update_pdf_content'
|
||||
import { triggerRule, TRIGGER_RULE_JOB_NAME } from './jobs/trigger_rule'
|
||||
|
||||
export const QUEUE_NAME = 'omnivore-backend-queue'
|
||||
|
||||
|
|
@ -39,8 +41,8 @@ const main = async () => {
|
|||
const port = process.env.PORT || 3002
|
||||
|
||||
redisDataSource.setOptions({
|
||||
REDIS_URL: env.redis.url,
|
||||
REDIS_CERT: env.redis.cert,
|
||||
cache: env.redis.cache,
|
||||
mq: env.redis.mq,
|
||||
})
|
||||
|
||||
appDataSource.setOptions({
|
||||
|
|
@ -63,6 +65,26 @@ const main = async () => {
|
|||
// respond healthy to auto-scaler.
|
||||
app.get('/_ah/health', (req, res) => res.sendStatus(200))
|
||||
|
||||
app.get('/metrics', async (_, res) => {
|
||||
const queue = await getBackendQueue()
|
||||
if (!queue) {
|
||||
res.sendStatus(400)
|
||||
return
|
||||
}
|
||||
|
||||
let output = ''
|
||||
const metrics: JobType[] = ['active', 'failed', 'completed', 'prioritized']
|
||||
const counts = await queue.getJobCounts(...metrics)
|
||||
console.log('counts: ', counts)
|
||||
|
||||
metrics.forEach((metric, idx) => {
|
||||
output += `# TYPE omnivore_queue_messages_${metric} gauge\n`
|
||||
output += `omnivore_queue_messages_${metric}{queue="${QUEUE_NAME}"} ${counts[metric]}\n`
|
||||
})
|
||||
|
||||
res.status(200).setHeader('Content-Type', 'text/plain').send(output)
|
||||
})
|
||||
|
||||
const server = app.listen(port, () => {
|
||||
console.log(`[queue-processor]: started`)
|
||||
})
|
||||
|
|
@ -78,17 +100,14 @@ const main = async () => {
|
|||
throw '[queue-processor] error redis is not initialized'
|
||||
}
|
||||
|
||||
const queue = new Queue(QUEUE_NAME, {
|
||||
connection: workerRedisClient,
|
||||
})
|
||||
|
||||
const worker = new Worker(
|
||||
QUEUE_NAME,
|
||||
async (job: Job) => {
|
||||
switch (job.name) {
|
||||
case 'refresh-all-feeds': {
|
||||
const counts = await queue.getJobCounts('wait')
|
||||
if (counts.wait > 1000) {
|
||||
const queue = await getBackendQueue()
|
||||
const counts = await queue?.getJobCounts('prioritized')
|
||||
if (counts && counts.wait > 1000) {
|
||||
return
|
||||
}
|
||||
return await refreshAllFeeds(appDataSource)
|
||||
|
|
@ -102,8 +121,11 @@ const main = async () => {
|
|||
case 'update-pdf-content': {
|
||||
return updatePDFContentJob(job.data)
|
||||
}
|
||||
case THUMBNAIL_JOB:
|
||||
return findThumbnail(job.data)
|
||||
case TRIGGER_RULE_JOB_NAME:
|
||||
return triggerRule(job.data)
|
||||
}
|
||||
return true
|
||||
},
|
||||
{
|
||||
connection: workerRedisClient,
|
||||
|
|
|
|||
1
packages/api/src/readability.d.ts
vendored
1
packages/api/src/readability.d.ts
vendored
|
|
@ -166,6 +166,7 @@ declare module '@omnivore/readability' {
|
|||
/** Article published date */
|
||||
publishedDate?: Date | null
|
||||
language?: string | null
|
||||
documentElement: HTMLElement
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,14 @@
|
|||
import Redis, { RedisOptions } from 'ioredis'
|
||||
import { env } from './env'
|
||||
import { logger } from './utils/logger'
|
||||
|
||||
type RedisClientType = 'cache' | 'mq'
|
||||
type RedisDataSourceOption = {
|
||||
url?: string
|
||||
cert?: string
|
||||
}
|
||||
export type RedisDataSourceOptions = {
|
||||
REDIS_URL?: string
|
||||
REDIS_CERT?: string
|
||||
[key in RedisClientType]: RedisDataSourceOption
|
||||
}
|
||||
|
||||
export class RedisDataSource {
|
||||
|
|
@ -22,8 +27,9 @@ export class RedisDataSource {
|
|||
async initialize(): Promise<this> {
|
||||
if (this.isInitialized) throw 'Error already initialized'
|
||||
|
||||
this.redisClient = createIORedisClient('app', this.options)
|
||||
this.workerRedisClient = createIORedisClient('worker', this.options)
|
||||
this.redisClient = createIORedisClient('cache', this.options)
|
||||
this.workerRedisClient =
|
||||
createIORedisClient('mq', this.options) || this.redisClient // if mq is not defined, use cache
|
||||
this.isInitialized = true
|
||||
|
||||
return Promise.resolve(this)
|
||||
|
|
@ -39,23 +45,27 @@ export class RedisDataSource {
|
|||
await this.workerRedisClient?.quit()
|
||||
await this.redisClient?.quit()
|
||||
} catch (err) {
|
||||
console.error('error while shutting down redis', err)
|
||||
logger.error('error while shutting down redis', err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const createIORedisClient = (
|
||||
name: string,
|
||||
name: RedisClientType,
|
||||
options: RedisDataSourceOptions
|
||||
): Redis | undefined => {
|
||||
const redisURL = options.REDIS_URL
|
||||
const option = options[name]
|
||||
const redisURL = option.url
|
||||
if (!redisURL) {
|
||||
throw 'Error: no redisURL supplied'
|
||||
logger.info(`no redisURL supplied: ${name}`)
|
||||
return undefined
|
||||
}
|
||||
|
||||
const redisCert = option.cert
|
||||
const tls =
|
||||
redisURL.startsWith('rediss://') && options.REDIS_CERT
|
||||
redisURL.startsWith('rediss://') && redisCert
|
||||
? {
|
||||
ca: options.REDIS_CERT,
|
||||
ca: redisCert,
|
||||
rejectUnauthorized: false,
|
||||
}
|
||||
: undefined
|
||||
|
|
@ -92,7 +102,6 @@ const createIORedisClient = (
|
|||
return new Redis(redisURL, redisOptions)
|
||||
}
|
||||
|
||||
export const redisDataSource = new RedisDataSource({
|
||||
REDIS_URL: env.redis.url,
|
||||
REDIS_CERT: env.redis.cert,
|
||||
})
|
||||
export const redisDataSource = new RedisDataSource(
|
||||
env.redis as RedisDataSourceOptions
|
||||
)
|
||||
|
|
|
|||
|
|
@ -87,11 +87,13 @@ import {
|
|||
import { parsedContentToLibraryItem } from '../../services/save_page'
|
||||
import {
|
||||
findUploadFileById,
|
||||
itemTypeForContentType,
|
||||
setFileUploadComplete,
|
||||
} from '../../services/upload_file'
|
||||
import { traceAs } from '../../tracing'
|
||||
import { analytics } from '../../utils/analytics'
|
||||
import { isSiteBlockedForParse } from '../../utils/blocked'
|
||||
import { authorized } from '../../utils/gql-utils'
|
||||
import {
|
||||
cleanUrl,
|
||||
errorHandler,
|
||||
|
|
@ -102,7 +104,6 @@ import {
|
|||
titleForFilePath,
|
||||
userDataToUser,
|
||||
} from '../../utils/helpers'
|
||||
import { authorized } from '../../utils/gql-utils'
|
||||
import {
|
||||
contentConverter,
|
||||
getDistillerResult,
|
||||
|
|
@ -111,7 +112,6 @@ import {
|
|||
parsePreparedContent,
|
||||
} from '../../utils/parser'
|
||||
import { getStorageFileDetails } from '../../utils/uploads'
|
||||
import { itemTypeForContentType } from '../upload_files'
|
||||
|
||||
export enum ArticleFormat {
|
||||
Markdown = 'markdown',
|
||||
|
|
@ -908,7 +908,12 @@ export const setFavoriteArticleResolver = authorized<
|
|||
|
||||
const labels = await findOrCreateLabels([label], uid)
|
||||
// adds Favorites label to item
|
||||
await addLabelsToLibraryItem(labels, id, uid)
|
||||
await addLabelsToLibraryItem(
|
||||
labels.map((l) => l.id),
|
||||
id,
|
||||
uid,
|
||||
'user'
|
||||
)
|
||||
|
||||
return {
|
||||
success: true,
|
||||
|
|
|
|||
|
|
@ -477,6 +477,10 @@ export const functionResolvers = {
|
|||
DEFAULT_SUBSCRIPTION_FOLDER
|
||||
)
|
||||
},
|
||||
// for campability with old clients
|
||||
lastFetchedAt(subscription: Subscription) {
|
||||
return subscription.refreshedAt
|
||||
},
|
||||
},
|
||||
NewsletterEmail: {
|
||||
subscriptionCount(newsletterEmail: NewsletterEmail) {
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import { Brackets, In } from 'typeorm'
|
|||
import {
|
||||
DEFAULT_SUBSCRIPTION_FOLDER,
|
||||
Subscription,
|
||||
SubscriptionStatus,
|
||||
SubscriptionType,
|
||||
} from '../../entity/subscription'
|
||||
import { env } from '../../env'
|
||||
import {
|
||||
|
|
@ -28,8 +30,6 @@ import {
|
|||
SubscriptionsError,
|
||||
SubscriptionsErrorCode,
|
||||
SubscriptionsSuccess,
|
||||
SubscriptionStatus,
|
||||
SubscriptionType,
|
||||
UnsubscribeError,
|
||||
UnsubscribeErrorCode,
|
||||
UnsubscribeSuccess,
|
||||
|
|
@ -41,13 +41,13 @@ import { getRepository } from '../../repository'
|
|||
import { feedRepository } from '../../repository/feed'
|
||||
import { validateUrl } from '../../services/create_page_save_request'
|
||||
import { unsubscribe } from '../../services/subscriptions'
|
||||
import { updateSubscription } from '../../services/update_subscription'
|
||||
import { Merge } from '../../util'
|
||||
import { analytics } from '../../utils/analytics'
|
||||
import { enqueueRssFeedFetch } from '../../utils/createTask'
|
||||
import { getAbsoluteUrl, keysToCamelCase } from '../../utils/helpers'
|
||||
import { authorized } from '../../utils/gql-utils'
|
||||
import { getAbsoluteUrl, keysToCamelCase } from '../../utils/helpers'
|
||||
import { parseFeed, parseOpml, RSS_PARSER_CONFIG } from '../../utils/parser'
|
||||
import { updateSubscription } from '../../services/update_subscription'
|
||||
|
||||
type PartialSubscription = Omit<Subscription, 'newsletterEmail'>
|
||||
|
||||
|
|
@ -61,8 +61,7 @@ export const subscriptionsResolver = authorized<
|
|||
QuerySubscriptionsArgs
|
||||
>(async (_obj, { sort, type }, { uid, log }) => {
|
||||
try {
|
||||
const sortBy =
|
||||
sort?.by === SortBy.UpdatedTime ? 'lastFetchedAt' : 'createdAt'
|
||||
const sortBy = sort?.by === SortBy.UpdatedTime ? 'refreshedAt' : 'createdAt'
|
||||
const sortOrder = sort?.order === SortOrder.Ascending ? 'ASC' : 'DESC'
|
||||
|
||||
const queryBuilder = getRepository(Subscription)
|
||||
|
|
@ -239,7 +238,7 @@ export const subscribeResolver = authorized<
|
|||
url: feedUrl,
|
||||
subscriptionIds: [updatedSubscription.id],
|
||||
scheduledDates: [new Date()], // fetch immediately
|
||||
fetchedDates: [updatedSubscription.lastFetchedAt || null],
|
||||
mostRecentItemDates: [updatedSubscription.mostRecentItemDate || null],
|
||||
checksums: [updatedSubscription.lastFetchedChecksum || null],
|
||||
fetchContents: [updatedSubscription.fetchContent],
|
||||
folders: [updatedSubscription.folder || DEFAULT_SUBSCRIPTION_FOLDER],
|
||||
|
|
@ -289,7 +288,7 @@ export const subscribeResolver = authorized<
|
|||
url: feedUrl,
|
||||
subscriptionIds: [newSubscription.id],
|
||||
scheduledDates: [new Date()], // fetch immediately
|
||||
fetchedDates: [null],
|
||||
mostRecentItemDates: [null],
|
||||
checksums: [null],
|
||||
fetchContents: [newSubscription.fetchContent],
|
||||
folders: [newSubscription.folder || DEFAULT_SUBSCRIPTION_FOLDER],
|
||||
|
|
@ -319,7 +318,7 @@ export const updateSubscriptionResolver = authorized<
|
|||
UpdateSubscriptionSuccessPartial,
|
||||
UpdateSubscriptionError,
|
||||
MutationUpdateSubscriptionArgs
|
||||
>(async (_, { input }, { authTrx, uid, log }) => {
|
||||
>(async (_, { input }, { uid, log }) => {
|
||||
try {
|
||||
analytics.track({
|
||||
userId: uid,
|
||||
|
|
|
|||
|
|
@ -1,55 +1,17 @@
|
|||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import normalizeUrl from 'normalize-url'
|
||||
import path from 'path'
|
||||
import { LibraryItemState } from '../../entity/library_item'
|
||||
import { UploadFile } from '../../entity/upload_file'
|
||||
import { env } from '../../env'
|
||||
import {
|
||||
MutationUploadFileRequestArgs,
|
||||
PageType,
|
||||
UploadFileRequestError,
|
||||
UploadFileRequestErrorCode,
|
||||
UploadFileRequestSuccess,
|
||||
UploadFileStatus,
|
||||
} from '../../generated/graphql'
|
||||
import { validateUrl } from '../../services/create_page_save_request'
|
||||
import {
|
||||
createLibraryItem,
|
||||
findLibraryItemByUrl,
|
||||
updateLibraryItem,
|
||||
} from '../../services/library_item'
|
||||
import { uploadFile } from '../../services/upload_file'
|
||||
import { analytics } from '../../utils/analytics'
|
||||
import { generateSlug } from '../../utils/helpers'
|
||||
import { authorized } from '../../utils/gql-utils'
|
||||
|
||||
import {
|
||||
contentReaderForLibraryItem,
|
||||
generateUploadFilePathName,
|
||||
generateUploadSignedUrl,
|
||||
} from '../../utils/uploads'
|
||||
|
||||
const isFileUrl = (url: string): boolean => {
|
||||
const parsedUrl = new URL(url)
|
||||
return parsedUrl.protocol == 'file:'
|
||||
}
|
||||
|
||||
export const itemTypeForContentType = (contentType: string) => {
|
||||
if (contentType == 'application/epub+zip') {
|
||||
return PageType.Book
|
||||
}
|
||||
return PageType.File
|
||||
}
|
||||
|
||||
export const uploadFileRequestResolver = authorized<
|
||||
UploadFileRequestSuccess,
|
||||
UploadFileRequestError,
|
||||
MutationUploadFileRequestArgs
|
||||
>(async (_, { input }, ctx) => {
|
||||
const { authTrx, uid, log } = ctx
|
||||
let uploadFileData: { id: string | null } = {
|
||||
id: null,
|
||||
}
|
||||
|
||||
>(async (_, { input }, { uid }) => {
|
||||
analytics.track({
|
||||
userId: uid,
|
||||
event: 'file_upload_request',
|
||||
|
|
@ -59,112 +21,5 @@ export const uploadFileRequestResolver = authorized<
|
|||
},
|
||||
})
|
||||
|
||||
let title: string
|
||||
let fileName: string
|
||||
try {
|
||||
const url = normalizeUrl(new URL(input.url).href, {
|
||||
stripHash: true,
|
||||
stripWWW: false,
|
||||
})
|
||||
title = decodeURI(path.basename(new URL(url).pathname, '.pdf'))
|
||||
fileName = decodeURI(path.basename(new URL(url).pathname)).replace(
|
||||
/[^a-zA-Z0-9-_.]/g,
|
||||
''
|
||||
)
|
||||
|
||||
if (!fileName) {
|
||||
fileName = 'content.pdf'
|
||||
}
|
||||
|
||||
if (!isFileUrl(url)) {
|
||||
try {
|
||||
validateUrl(url)
|
||||
} catch (error) {
|
||||
log.info('illegal file input url', error)
|
||||
return {
|
||||
errorCodes: [UploadFileRequestErrorCode.BadInput],
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return { errorCodes: [UploadFileRequestErrorCode.BadInput] }
|
||||
}
|
||||
|
||||
uploadFileData = await authTrx((t) =>
|
||||
t.getRepository(UploadFile).save({
|
||||
url: input.url,
|
||||
user: { id: uid },
|
||||
fileName,
|
||||
status: UploadFileStatus.Initialized,
|
||||
contentType: input.contentType,
|
||||
})
|
||||
)
|
||||
|
||||
if (uploadFileData.id) {
|
||||
const uploadFileId = uploadFileData.id
|
||||
const uploadFilePathName = generateUploadFilePathName(
|
||||
uploadFileId,
|
||||
fileName
|
||||
)
|
||||
const uploadSignedUrl = await generateUploadSignedUrl(
|
||||
uploadFilePathName,
|
||||
input.contentType
|
||||
)
|
||||
|
||||
// If this is a file URL, we swap in a special URL
|
||||
const attachmentUrl = `https://omnivore.app/attachments/${uploadFilePathName}`
|
||||
if (isFileUrl(input.url)) {
|
||||
await authTrx(async (tx) => {
|
||||
await tx.getRepository(UploadFile).update(uploadFileId, {
|
||||
url: attachmentUrl,
|
||||
status: UploadFileStatus.Initialized,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
let createdItemId: string | undefined = undefined
|
||||
if (input.createPageEntry) {
|
||||
// If we have a file:// URL, don't try to match it
|
||||
// and create a copy of the item, just create a
|
||||
// new item.
|
||||
const item = await findLibraryItemByUrl(input.url, uid)
|
||||
if (item) {
|
||||
await updateLibraryItem(
|
||||
item.id,
|
||||
{
|
||||
state: LibraryItemState.Processing,
|
||||
},
|
||||
uid
|
||||
)
|
||||
createdItemId = item.id
|
||||
} else {
|
||||
const itemType = itemTypeForContentType(input.contentType)
|
||||
const uploadFileId = uploadFileData.id
|
||||
const item = await createLibraryItem(
|
||||
{
|
||||
id: input.clientRequestId || undefined,
|
||||
originalUrl: isFileUrl(input.url) ? attachmentUrl : input.url,
|
||||
user: { id: uid },
|
||||
title,
|
||||
readableContent: '',
|
||||
itemType,
|
||||
uploadFile: { id: uploadFileData.id },
|
||||
slug: generateSlug(uploadFilePathName),
|
||||
state: LibraryItemState.Processing,
|
||||
contentReader: contentReaderForLibraryItem(itemType, uploadFileId),
|
||||
},
|
||||
uid
|
||||
)
|
||||
createdItemId = item.id
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: uploadFileData.id,
|
||||
uploadSignedUrl,
|
||||
createdPageId: createdItemId,
|
||||
}
|
||||
} else {
|
||||
return { errorCodes: [UploadFileRequestErrorCode.FailedCreate] }
|
||||
}
|
||||
return uploadFile(input, uid)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ export function contentServiceRouter() {
|
|||
const router = express.Router()
|
||||
|
||||
router.post('/search', async (req, res) => {
|
||||
logger.info('search req', req)
|
||||
const { message: msgStr, expired } = readPushSubscription(req)
|
||||
logger.info('read pubsub message', { msgStr, expired })
|
||||
|
||||
|
|
|
|||
|
|
@ -53,15 +53,13 @@ export function followingServiceRouter() {
|
|||
const router = express.Router()
|
||||
|
||||
router.post('/save', async (req, res) => {
|
||||
logger.info('save following item request', req.body)
|
||||
|
||||
if (req.query.token !== process.env.PUBSUB_VERIFICATION_TOKEN) {
|
||||
console.log('query does not include valid token')
|
||||
logger.info('query does not include valid token')
|
||||
return res.sendStatus(403)
|
||||
}
|
||||
|
||||
if (!isSaveFollowingItemRequest(req.body)) {
|
||||
console.error('Invalid request body', req.body)
|
||||
logger.error('Invalid request body', req.body)
|
||||
return res.status(400).send('INVALID_REQUEST_BODY')
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ const getPruneMessage = (msgStr: string): PruneMessage => {
|
|||
return obj
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('error deserializing event: ', { msgStr, err })
|
||||
logger.error('error deserializing event: ', { msgStr, err })
|
||||
}
|
||||
|
||||
// default to prune following folder items older than 30 days
|
||||
|
|
@ -43,7 +43,6 @@ export function linkServiceRouter() {
|
|||
const router = express.Router()
|
||||
|
||||
router.post('/create', async (req, res) => {
|
||||
logger.info('create link req', req)
|
||||
const { message: msgStr, expired } = readPushSubscription(req)
|
||||
logger.info('read pubsub message', { msgStr, expired })
|
||||
|
||||
|
|
@ -71,7 +70,6 @@ export function linkServiceRouter() {
|
|||
userId: msg.userId,
|
||||
url: msg.url,
|
||||
})
|
||||
logger.info('create link request', request)
|
||||
|
||||
res.status(200).send(request)
|
||||
} catch (err) {
|
||||
|
|
@ -81,8 +79,6 @@ export function linkServiceRouter() {
|
|||
})
|
||||
|
||||
router.post('/prune', async (req, res) => {
|
||||
logger.info('prune expired items in folder')
|
||||
|
||||
const { message: msgStr, expired } = readPushSubscription(req)
|
||||
|
||||
if (!msgStr) {
|
||||
|
|
|
|||
|
|
@ -23,11 +23,11 @@ export function rssFeedRouter() {
|
|||
if (redisDataSource.workerRedisClient) {
|
||||
await queueRSSRefreshAllFeedsJob()
|
||||
} else {
|
||||
console.log('unable to fetchAll feeds, redis is not configured')
|
||||
logger.info('unable to fetchAll feeds, redis is not configured')
|
||||
return res.status(500).send('Expired')
|
||||
}
|
||||
} catch (error) {
|
||||
logger.info('error fetching rss feeds', error)
|
||||
logger.error('error fetching rss feeds', error)
|
||||
return res.status(500).send('Internal Server Error')
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ const getCleanupMessage = (msgStr: string): CleanupMessage => {
|
|||
return obj
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('error deserializing event: ', { msgStr, err })
|
||||
logger.error('error deserializing event: ', { msgStr, err })
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -545,6 +545,9 @@ const schema = gql`
|
|||
state: ArticleSavingRequestStatus
|
||||
labels: [CreateLabelInput!]
|
||||
folder: String
|
||||
savedAt: Date
|
||||
publishedAt: Date
|
||||
subscription: String
|
||||
}
|
||||
|
||||
input ParseResult {
|
||||
|
|
@ -1686,6 +1689,9 @@ const schema = gql`
|
|||
autoAddToLibrary: Boolean
|
||||
fetchContent: Boolean!
|
||||
folder: String!
|
||||
mostRecentItemDate: Date
|
||||
refreshedAt: Date
|
||||
failedAt: Date
|
||||
}
|
||||
|
||||
enum SubscriptionStatus {
|
||||
|
|
@ -2597,7 +2603,6 @@ const schema = gql`
|
|||
id: ID!
|
||||
name: String
|
||||
description: String
|
||||
lastFetchedAt: Date
|
||||
lastFetchedChecksum: String
|
||||
status: SubscriptionStatus
|
||||
scheduledAt: Date
|
||||
|
|
@ -2605,6 +2610,9 @@ const schema = gql`
|
|||
autoAddToLibrary: Boolean
|
||||
fetchContent: Boolean
|
||||
folder: String
|
||||
refreshedAt: Date
|
||||
mostRecentItemDate: Date
|
||||
failedAt: Date
|
||||
}
|
||||
|
||||
union UpdateSubscriptionResult =
|
||||
|
|
|
|||
|
|
@ -159,7 +159,7 @@ const main = async (): Promise<void> => {
|
|||
await appDataSource.initialize()
|
||||
|
||||
// redis is optional for the API server
|
||||
if (env.redis.url) {
|
||||
if (env.redis.cache.url) {
|
||||
await redisDataSource.initialize()
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import { Label } from '../entity/label'
|
|||
import { createPubSubClient, EntityType, PubsubClient } from '../pubsub'
|
||||
import { authTrx } from '../repository'
|
||||
import { CreateLabelInput, labelRepository } from '../repository/label'
|
||||
import { libraryItemRepository } from '../repository/library_item'
|
||||
|
||||
type AddLabelsToLibraryItemEvent = {
|
||||
pageId: string
|
||||
|
|
@ -124,43 +123,28 @@ export const saveLabelsInLibraryItem = async (
|
|||
}
|
||||
|
||||
export const addLabelsToLibraryItem = async (
|
||||
labels: Label[],
|
||||
labelIds: string[],
|
||||
libraryItemId: string,
|
||||
userId: string,
|
||||
source: LabelSource = 'user',
|
||||
pubsub = createPubSubClient()
|
||||
source: LabelSource = 'user'
|
||||
) => {
|
||||
await authTrx(
|
||||
async (tx) => {
|
||||
const libraryItem = await tx
|
||||
.withRepository(libraryItemRepository)
|
||||
.findOneByOrFail({ id: libraryItemId, user: { id: userId } })
|
||||
|
||||
if (libraryItem.labels) {
|
||||
labels.push(...libraryItem.labels)
|
||||
}
|
||||
|
||||
// save new labels
|
||||
await tx.getRepository(EntityLabel).save(
|
||||
labels.map((l) => ({
|
||||
labelId: l.id,
|
||||
libraryItemId,
|
||||
source,
|
||||
}))
|
||||
await tx.query(
|
||||
`INSERT INTO omnivore.entity_labels (label_id, library_item_id, source)
|
||||
SELECT id, $1, $2 FROM omnivore.labels
|
||||
WHERE id = ANY($3)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM omnivore.entity_labels
|
||||
WHERE label_id = labels.id
|
||||
AND library_item_id = $1
|
||||
)`,
|
||||
[libraryItemId, source, labelIds]
|
||||
)
|
||||
},
|
||||
undefined,
|
||||
userId
|
||||
)
|
||||
|
||||
if (source === 'user') {
|
||||
// create pubsub event
|
||||
await pubsub.entityCreated<AddLabelsToLibraryItemEvent>(
|
||||
EntityType.LABEL,
|
||||
{ pageId: libraryItemId, labels, source },
|
||||
userId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export const saveLabelsInHighlight = async (
|
||||
|
|
|
|||
|
|
@ -698,7 +698,8 @@ export const updateLibraryItem = async (
|
|||
id: string,
|
||||
libraryItem: QueryDeepPartialEntity<LibraryItem>,
|
||||
userId: string,
|
||||
pubsub = createPubSubClient()
|
||||
pubsub = createPubSubClient(),
|
||||
skipPubSub = false
|
||||
): Promise<LibraryItem> => {
|
||||
const updatedLibraryItem = await authTrx(
|
||||
async (tx) => {
|
||||
|
|
@ -726,6 +727,10 @@ export const updateLibraryItem = async (
|
|||
userId
|
||||
)
|
||||
|
||||
if (skipPubSub) {
|
||||
return updatedLibraryItem
|
||||
}
|
||||
|
||||
await pubsub.entityUpdated<QueryDeepPartialEntity<LibraryItem>>(
|
||||
EntityType.PAGE,
|
||||
{
|
||||
|
|
|
|||
|
|
@ -33,18 +33,19 @@ export const saveContentDisplayReport = async (
|
|||
${report.user.id} for URL: ${report.originalUrl}
|
||||
${report.reportComment}`
|
||||
|
||||
logger.info(message)
|
||||
|
||||
if (!env.dev.isLocal) {
|
||||
// If we are in the local environment, just log a message, otherwise email the report
|
||||
await sendEmail({
|
||||
to: env.sender.feedback,
|
||||
subject: 'New content display report',
|
||||
text: message,
|
||||
from: env.sender.message,
|
||||
})
|
||||
// If we are in the local environment, just log a message, otherwise email the report
|
||||
if (env.dev.isLocal) {
|
||||
logger.info(message)
|
||||
return !!report
|
||||
}
|
||||
|
||||
await sendEmail({
|
||||
to: env.sender.feedback,
|
||||
subject: 'New content display report',
|
||||
text: message,
|
||||
from: env.sender.message,
|
||||
})
|
||||
|
||||
return !!report
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { ILike } from 'typeorm'
|
||||
import { Rule, RuleAction } from '../entity/rule'
|
||||
import { authTrx } from '../repository'
|
||||
import { ArrayContainedBy, ArrayContains, ILike } from 'typeorm'
|
||||
import { Rule, RuleAction, RuleEventType } from '../entity/rule'
|
||||
import { authTrx, getRepository } from '../repository'
|
||||
|
||||
export const createRule = async (
|
||||
userId: string,
|
||||
|
|
@ -53,3 +53,14 @@ export const deleteRules = async (userId: string) => {
|
|||
userId
|
||||
)
|
||||
}
|
||||
|
||||
export const findEnabledRules = async (
|
||||
userId: string,
|
||||
eventType: RuleEventType
|
||||
) => {
|
||||
return getRepository(Rule).findBy({
|
||||
user: { id: userId },
|
||||
enabled: true,
|
||||
eventTypes: ArrayContainedBy([eventType]),
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { LibraryItem, LibraryItemState } from '../entity/library_item'
|
||||
import { enqueueThumbnailTask } from '../utils/createTask'
|
||||
import { enqueueThumbnailJob } from '../utils/createTask'
|
||||
import {
|
||||
cleanUrl,
|
||||
generateSlug,
|
||||
|
|
@ -53,7 +53,6 @@ export const saveEmail = async (
|
|||
// can leave this empty for now
|
||||
},
|
||||
},
|
||||
null,
|
||||
true
|
||||
)
|
||||
|
||||
|
|
@ -76,7 +75,6 @@ export const saveEmail = async (
|
|||
existingLibraryItem.id,
|
||||
input.userId
|
||||
)
|
||||
logger.info('updated page from email', updatedLibraryItem)
|
||||
|
||||
return updatedLibraryItem
|
||||
}
|
||||
|
|
@ -133,12 +131,14 @@ export const saveEmail = async (
|
|||
|
||||
await updateReceivedEmail(input.receivedEmailId, 'article', input.userId)
|
||||
|
||||
// create a task to update thumbnail and pre-cache all images
|
||||
try {
|
||||
const taskId = await enqueueThumbnailTask(input.userId, slug)
|
||||
logger.info('Created thumbnail task', { taskId })
|
||||
} catch (e) {
|
||||
logger.error('Failed to create thumbnail task', e)
|
||||
if (!newLibraryItem.thumbnail) {
|
||||
// create a task to update thumbnail and pre-cache all images
|
||||
try {
|
||||
const job = await enqueueThumbnailJob(input.userId, newLibraryItem.id)
|
||||
logger.info('Created thumbnail job', { taskId: job })
|
||||
} catch (e) {
|
||||
logger.error('Failed to create thumbnail job', e)
|
||||
}
|
||||
}
|
||||
|
||||
return newLibraryItem
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ export const saveFile = async (
|
|||
const uploadFile = await findUploadFileById(input.uploadFileId)
|
||||
if (!uploadFile) {
|
||||
return {
|
||||
__typename: 'SaveError',
|
||||
errorCodes: [SaveErrorCode.Unauthorized],
|
||||
}
|
||||
}
|
||||
|
|
@ -24,26 +25,30 @@ export const saveFile = async (
|
|||
|
||||
if (!uploadFileData) {
|
||||
return {
|
||||
__typename: 'SaveError',
|
||||
errorCodes: [SaveErrorCode.Unknown],
|
||||
}
|
||||
}
|
||||
|
||||
if (input.state || input.folder) {
|
||||
await updateLibraryItem(
|
||||
input.clientRequestId,
|
||||
{
|
||||
state: (input.state as unknown as LibraryItemState) || undefined,
|
||||
folder: input.folder || undefined,
|
||||
},
|
||||
user.id
|
||||
)
|
||||
}
|
||||
await updateLibraryItem(
|
||||
input.clientRequestId,
|
||||
{
|
||||
state:
|
||||
(input.state as unknown as LibraryItemState) ||
|
||||
LibraryItemState.Succeeded,
|
||||
folder: input.folder || undefined,
|
||||
savedAt: input.savedAt ? new Date(input.savedAt) : undefined,
|
||||
publishedAt: input.publishedAt ? new Date(input.publishedAt) : undefined,
|
||||
},
|
||||
user.id
|
||||
)
|
||||
|
||||
// add labels to item
|
||||
await createAndSaveLabelsInLibraryItem(
|
||||
input.clientRequestId,
|
||||
user.id,
|
||||
input.labels
|
||||
input.labels,
|
||||
input.subscription
|
||||
)
|
||||
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -13,12 +13,11 @@ import {
|
|||
SaveResult,
|
||||
} from '../generated/graphql'
|
||||
import { authTrx } from '../repository'
|
||||
import { enqueueThumbnailTask } from '../utils/createTask'
|
||||
import { enqueueThumbnailJob } from '../utils/createTask'
|
||||
import {
|
||||
cleanUrl,
|
||||
generateSlug,
|
||||
stringToHash,
|
||||
TWEET_URL_REGEX,
|
||||
validatedDate,
|
||||
wordsCount,
|
||||
} from '../utils/helpers'
|
||||
|
|
@ -32,7 +31,7 @@ import { createLibraryItem, updateLibraryItem } from './library_item'
|
|||
|
||||
// where we can use APIs to fetch their underlying content.
|
||||
const FORCE_PUPPETEER_URLS = [
|
||||
TWEET_URL_REGEX,
|
||||
/twitter\.com\/(?:#!\/)?(\w+)\/status(?:es)?\/(\d+)(?:\/.*)?/,
|
||||
/^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/,
|
||||
]
|
||||
const ALREADY_PARSED_SOURCES = [
|
||||
|
|
@ -58,7 +57,9 @@ const createSlug = (url: string, title?: string | null | undefined) => {
|
|||
const shouldParseInBackend = (input: SavePageInput): boolean => {
|
||||
return (
|
||||
ALREADY_PARSED_SOURCES.indexOf(input.source) === -1 &&
|
||||
FORCE_PUPPETEER_URLS.some((regex) => regex.test(input.url))
|
||||
FORCE_PUPPETEER_URLS.some((regex) => {
|
||||
return regex.test(input.url)
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -66,17 +67,13 @@ export const savePage = async (
|
|||
input: SavePageInput,
|
||||
user: User
|
||||
): Promise<SaveResult> => {
|
||||
const parseResult = await parsePreparedContent(
|
||||
input.url,
|
||||
{
|
||||
document: input.originalContent,
|
||||
pageInfo: {
|
||||
title: input.title,
|
||||
canonicalUrl: input.url,
|
||||
},
|
||||
const parseResult = await parsePreparedContent(input.url, {
|
||||
document: input.originalContent,
|
||||
pageInfo: {
|
||||
title: input.title,
|
||||
canonicalUrl: input.url,
|
||||
},
|
||||
input.parseResult
|
||||
)
|
||||
})
|
||||
const [newSlug, croppedPathname] = createSlug(input.url, input.title)
|
||||
let slug = newSlug
|
||||
let clientRequestId = input.clientRequestId
|
||||
|
|
@ -114,6 +111,7 @@ export const savePage = async (
|
|||
})
|
||||
} catch (e) {
|
||||
return {
|
||||
__typename: 'SaveError',
|
||||
errorCodes: [SaveErrorCode.Unknown],
|
||||
message: 'Failed to create page save request',
|
||||
}
|
||||
|
|
@ -171,10 +169,10 @@ export const savePage = async (
|
|||
if (!isImported && !parseResult.parsedContent?.previewImage) {
|
||||
try {
|
||||
// create a task to update thumbnail and pre-cache all images
|
||||
const taskId = await enqueueThumbnailTask(user.id, slug)
|
||||
logger.info('Created thumbnail task', { taskId })
|
||||
const job = await enqueueThumbnailJob(user.id, clientRequestId)
|
||||
logger.info('Created thumbnail job', { job })
|
||||
} catch (e) {
|
||||
logger.error('Failed to create thumbnail task', e)
|
||||
logger.error('Failed to enqueue thumbnail job', e)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -185,11 +183,14 @@ export const savePage = async (
|
|||
libraryItem: { id: clientRequestId },
|
||||
}
|
||||
|
||||
if (!(await createHighlight(highlight, clientRequestId, user.id))) {
|
||||
return {
|
||||
errorCodes: [SaveErrorCode.EmbeddedHighlightFailed],
|
||||
message: 'Failed to save highlight',
|
||||
}
|
||||
try {
|
||||
await createHighlight(highlight, clientRequestId, user.id)
|
||||
} catch (error) {
|
||||
logger.error('Failed to create highlight', {
|
||||
highlight,
|
||||
clientRequestId,
|
||||
userId: user.id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -239,7 +240,7 @@ export const parsedContentToLibraryItem = ({
|
|||
rssFeedUrl?: string | null
|
||||
folder?: string | null
|
||||
}): DeepPartial<LibraryItem> & { originalUrl: string } => {
|
||||
console.log('save_page: state', { url, state, itemId })
|
||||
logger.info('save_page: state', { url, state, itemId })
|
||||
return {
|
||||
id: itemId || undefined,
|
||||
slug,
|
||||
|
|
|
|||
|
|
@ -103,7 +103,7 @@ export const saveSubscription = async ({
|
|||
unsubscribeHttpUrl,
|
||||
unsubscribeMailTo,
|
||||
icon,
|
||||
lastFetchedAt: new Date(),
|
||||
refreshedAt: new Date(),
|
||||
}
|
||||
|
||||
const existingSubscription = await getSubscriptionByName(name, userId)
|
||||
|
|
@ -199,7 +199,7 @@ export const createSubscription = async (
|
|||
newsletterEmail,
|
||||
status,
|
||||
unsubscribeMailTo,
|
||||
lastFetchedAt: new Date(),
|
||||
refreshedAt: new Date(),
|
||||
type: subscriptionType,
|
||||
url,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,8 +1,4 @@
|
|||
import { Subscription } from '../entity/subscription'
|
||||
import {
|
||||
SubscriptionStatus,
|
||||
UpdateSubscriptionInput,
|
||||
} from '../generated/graphql'
|
||||
import { Subscription, SubscriptionStatus } from '../entity/subscription'
|
||||
import { getRepository } from '../repository'
|
||||
|
||||
const ensureOwns = async (userId: string, subscriptionId: string) => {
|
||||
|
|
@ -23,11 +19,13 @@ type UpdateSubscriptionData = {
|
|||
fetchContent?: boolean | null
|
||||
folder?: string | null
|
||||
isPrivate?: boolean | null
|
||||
lastFetchedAt?: Date | null
|
||||
mostRecentItemDate?: Date | null
|
||||
lastFetchedChecksum?: string | null
|
||||
name?: string | null
|
||||
scheduledAt?: Date | null
|
||||
status?: SubscriptionStatus | null
|
||||
refreshedAt?: Date | null
|
||||
failedAt?: Date | null
|
||||
}
|
||||
|
||||
export const updateSubscription = async (
|
||||
|
|
@ -42,22 +40,43 @@ export const updateSubscription = async (
|
|||
id: subscriptionId,
|
||||
name: newData.name || undefined,
|
||||
description: newData.description || undefined,
|
||||
lastFetchedAt: newData.lastFetchedAt
|
||||
? new Date(newData.lastFetchedAt)
|
||||
: undefined,
|
||||
mostRecentItemDate: newData.mostRecentItemDate || undefined,
|
||||
refreshedAt: newData.refreshedAt || undefined,
|
||||
lastFetchedChecksum: newData.lastFetchedChecksum || undefined,
|
||||
status: newData.status || undefined,
|
||||
scheduledAt: newData.scheduledAt
|
||||
? new Date(newData.scheduledAt)
|
||||
: undefined,
|
||||
scheduledAt: newData.scheduledAt || undefined,
|
||||
failedAt: newData.failedAt || undefined,
|
||||
autoAddToLibrary: newData.autoAddToLibrary ?? undefined,
|
||||
isPrivate: newData.isPrivate ?? undefined,
|
||||
fetchContent: newData.fetchContent ?? undefined,
|
||||
folder: newData.folder ?? undefined,
|
||||
})
|
||||
|
||||
return await getRepository(Subscription).findOneByOrFail({
|
||||
return await repo.findOneByOrFail({
|
||||
id: subscriptionId,
|
||||
user: { id: userId },
|
||||
})
|
||||
}
|
||||
|
||||
export const updateSubscriptions = async (
|
||||
subscriptionIds: string[],
|
||||
newData: UpdateSubscriptionData
|
||||
) => {
|
||||
return getRepository(Subscription).save(
|
||||
subscriptionIds.map((id) => ({
|
||||
id,
|
||||
name: newData.name || undefined,
|
||||
description: newData.description || undefined,
|
||||
mostRecentItemDate: newData.mostRecentItemDate || undefined,
|
||||
refreshedAt: newData.refreshedAt || undefined,
|
||||
lastFetchedChecksum: newData.lastFetchedChecksum || undefined,
|
||||
status: newData.status || undefined,
|
||||
scheduledAt: newData.scheduledAt || undefined,
|
||||
failedAt: newData.failedAt || undefined,
|
||||
autoAddToLibrary: newData.autoAddToLibrary ?? undefined,
|
||||
isPrivate: newData.isPrivate ?? undefined,
|
||||
fetchContent: newData.fetchContent ?? undefined,
|
||||
folder: newData.folder ?? undefined,
|
||||
}))
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,35 @@
|
|||
import normalizeUrl from 'normalize-url'
|
||||
import path from 'path'
|
||||
import { LibraryItemState } from '../entity/library_item'
|
||||
import { UploadFile } from '../entity/upload_file'
|
||||
import {
|
||||
PageType,
|
||||
UploadFileRequestErrorCode,
|
||||
UploadFileRequestInput,
|
||||
UploadFileStatus,
|
||||
} from '../generated/graphql'
|
||||
import { authTrx, getRepository } from '../repository'
|
||||
import { generateSlug } from '../utils/helpers'
|
||||
import { logger } from '../utils/logger'
|
||||
import {
|
||||
contentReaderForLibraryItem,
|
||||
generateUploadFilePathName,
|
||||
generateUploadSignedUrl,
|
||||
} from '../utils/uploads'
|
||||
import { validateUrl } from './create_page_save_request'
|
||||
import { createLibraryItem } from './library_item'
|
||||
|
||||
const isFileUrl = (url: string): boolean => {
|
||||
const parsedUrl = new URL(url)
|
||||
return parsedUrl.protocol == 'file:'
|
||||
}
|
||||
|
||||
export const itemTypeForContentType = (contentType: string) => {
|
||||
if (contentType == 'application/epub+zip') {
|
||||
return PageType.Book
|
||||
}
|
||||
return PageType.File
|
||||
}
|
||||
|
||||
export const findUploadFileById = async (id: string) => {
|
||||
return getRepository(UploadFile).findOne({
|
||||
|
|
@ -22,3 +52,100 @@ export const setFileUploadComplete = async (id: string, userId?: string) => {
|
|||
userId
|
||||
)
|
||||
}
|
||||
|
||||
export const uploadFile = async (
|
||||
input: UploadFileRequestInput,
|
||||
uid: string
|
||||
) => {
|
||||
let title: string
|
||||
let fileName: string
|
||||
try {
|
||||
const url = normalizeUrl(new URL(input.url).href, {
|
||||
stripHash: true,
|
||||
stripWWW: false,
|
||||
})
|
||||
title = decodeURI(path.basename(new URL(url).pathname, '.pdf'))
|
||||
fileName = decodeURI(path.basename(new URL(url).pathname)).replace(
|
||||
/[^a-zA-Z0-9-_.]/g,
|
||||
''
|
||||
)
|
||||
|
||||
if (!fileName) {
|
||||
fileName = 'content.pdf'
|
||||
}
|
||||
|
||||
if (!isFileUrl(url)) {
|
||||
try {
|
||||
validateUrl(url)
|
||||
} catch (error) {
|
||||
logger.info('illegal file input url', error)
|
||||
return {
|
||||
errorCodes: [UploadFileRequestErrorCode.BadInput],
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return {
|
||||
errorCodes: [UploadFileRequestErrorCode.BadInput],
|
||||
}
|
||||
}
|
||||
|
||||
const uploadFileData = await authTrx((t) =>
|
||||
t.getRepository(UploadFile).save({
|
||||
url: input.url,
|
||||
user: { id: uid },
|
||||
fileName,
|
||||
status: UploadFileStatus.Initialized,
|
||||
contentType: input.contentType,
|
||||
})
|
||||
)
|
||||
const uploadFileId = uploadFileData.id
|
||||
const uploadFilePathName = generateUploadFilePathName(uploadFileId, fileName)
|
||||
const uploadSignedUrl = await generateUploadSignedUrl(
|
||||
uploadFilePathName,
|
||||
input.contentType
|
||||
)
|
||||
|
||||
// If this is a file URL, we swap in a special URL
|
||||
const attachmentUrl = `https://omnivore.app/attachments/${uploadFilePathName}`
|
||||
if (isFileUrl(input.url)) {
|
||||
await authTrx(async (tx) => {
|
||||
await tx.getRepository(UploadFile).update(uploadFileId, {
|
||||
url: attachmentUrl,
|
||||
status: UploadFileStatus.Initialized,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const itemType = itemTypeForContentType(input.contentType)
|
||||
if (input.createPageEntry) {
|
||||
// If we have a file:// URL, don't try to match it
|
||||
// and create a copy of the item, just create a
|
||||
// new item.
|
||||
const item = await createLibraryItem(
|
||||
{
|
||||
id: input.clientRequestId || undefined,
|
||||
originalUrl: isFileUrl(input.url) ? attachmentUrl : input.url,
|
||||
user: { id: uid },
|
||||
title,
|
||||
readableContent: '',
|
||||
itemType,
|
||||
uploadFile: { id: uploadFileData.id },
|
||||
slug: generateSlug(uploadFilePathName),
|
||||
state: LibraryItemState.Processing,
|
||||
contentReader: contentReaderForLibraryItem(itemType, uploadFileId),
|
||||
},
|
||||
uid
|
||||
)
|
||||
return {
|
||||
id: uploadFileId,
|
||||
uploadSignedUrl,
|
||||
createdPageId: item.id,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: uploadFileId,
|
||||
uploadSignedUrl,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,15 @@
|
|||
import { Notification } from 'firebase-admin/messaging'
|
||||
import { DeepPartial, FindOptionsWhere, In } from 'typeorm'
|
||||
import { Profile } from '../entity/profile'
|
||||
import { StatusType, User } from '../entity/user'
|
||||
import { authTrx, getRepository, queryBuilderToRawSql } from '../repository'
|
||||
import { userRepository } from '../repository/user'
|
||||
import { SetClaimsRole } from '../utils/dictionary'
|
||||
import {
|
||||
PushNotificationType,
|
||||
sendMulticastPushNotifications,
|
||||
} from '../utils/sendNotification'
|
||||
import { findDeviceTokensByUserId } from './user_device_tokens'
|
||||
|
||||
export const deleteUser = async (userId: string) => {
|
||||
await authTrx(
|
||||
|
|
@ -120,3 +126,23 @@ export const batchDelete = async (criteria: FindOptionsWhere<User>) => {
|
|||
SetClaimsRole.ADMIN
|
||||
)
|
||||
}
|
||||
|
||||
export const sendPushNotifications = async (
|
||||
userId: string,
|
||||
notification: Notification,
|
||||
notificationType: PushNotificationType,
|
||||
data?: { [key: string]: string }
|
||||
) => {
|
||||
const tokens = await findDeviceTokensByUserId(userId)
|
||||
if (tokens.length === 0) {
|
||||
throw new Error('No device tokens found')
|
||||
}
|
||||
|
||||
const message = {
|
||||
notification,
|
||||
data,
|
||||
tokens: tokens.map((token) => token.token),
|
||||
}
|
||||
|
||||
return sendMulticastPushNotifications(userId, message, notificationType)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,11 @@
|
|||
import * as dotenv from 'dotenv'
|
||||
import os from 'os'
|
||||
|
||||
interface redisConfig {
|
||||
url?: string
|
||||
cert?: string
|
||||
}
|
||||
|
||||
export interface BackendEnv {
|
||||
pg: {
|
||||
host: string
|
||||
|
|
@ -105,8 +110,8 @@ export interface BackendEnv {
|
|||
}
|
||||
}
|
||||
redis: {
|
||||
url?: string
|
||||
cert?: string
|
||||
mq: redisConfig
|
||||
cache: redisConfig
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -156,6 +161,8 @@ const nullableEnvVars = [
|
|||
'SUBSCRIPTION_FEED_MAX',
|
||||
'REDIS_URL',
|
||||
'REDIS_CERT',
|
||||
'MQ_REDIS_URL',
|
||||
'MQ_REDIS_CERT',
|
||||
'IMPORTER_METRICS_COLLECTOR_URL',
|
||||
'INTERNAL_API_URL',
|
||||
] // Allow some vars to be null/empty
|
||||
|
|
@ -295,8 +302,14 @@ export function getEnv(): BackendEnv {
|
|||
},
|
||||
}
|
||||
const redis = {
|
||||
url: parse('REDIS_URL'),
|
||||
cert: parse('REDIS_CERT')?.replace(/\\n/g, '\n'), // replace \n with new line
|
||||
mq: {
|
||||
url: parse('MQ_REDIS_URL'),
|
||||
cert: parse('MQ_REDIS_CERT')?.replace(/\\n/g, '\n'), // replace \n with new line
|
||||
},
|
||||
cache: {
|
||||
url: parse('REDIS_URL'),
|
||||
cert: parse('REDIS_CERT')?.replace(/\\n/g, '\n'), // replace \n with new line
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -6,23 +6,25 @@ import { google } from '@google-cloud/tasks/build/protos/protos'
|
|||
import axios from 'axios'
|
||||
import { nanoid } from 'nanoid'
|
||||
import { DeepPartial } from 'typeorm'
|
||||
import { v4 as uuid } from 'uuid'
|
||||
import { ImportItemState } from '../entity/integration'
|
||||
import { Recommendation } from '../entity/recommendation'
|
||||
import { DEFAULT_SUBSCRIPTION_FOLDER } from '../entity/subscription'
|
||||
import { env } from '../env'
|
||||
import {
|
||||
ArticleSavingRequestStatus,
|
||||
CreateLabelInput,
|
||||
} from '../generated/graphql'
|
||||
import { THUMBNAIL_JOB } from '../jobs/find_thumbnail'
|
||||
import { queueRSSRefreshFeedJob } from '../jobs/rss/refreshAllFeeds'
|
||||
import { TriggerRuleJobData, TRIGGER_RULE_JOB_NAME } from '../jobs/trigger_rule'
|
||||
import { getBackendQueue } from '../queue-processor'
|
||||
import { redisDataSource } from '../redis_data_source'
|
||||
import { signFeatureToken } from '../services/features'
|
||||
import { generateVerificationToken, OmnivoreAuthorizationHeader } from './auth'
|
||||
import { OmnivoreAuthorizationHeader } from './auth'
|
||||
import { CreateTaskError } from './errors'
|
||||
import { stringToHash } from './helpers'
|
||||
import { logger } from './logger'
|
||||
import View = google.cloud.tasks.v2.Task.View
|
||||
import { stringToHash } from './helpers'
|
||||
import { queueRSSRefreshFeedJob } from '../jobs/rss/refreshAllFeeds'
|
||||
import { redisDataSource } from '../redis_data_source'
|
||||
import { v4 as uuid } from 'uuid'
|
||||
|
||||
// Instantiates a client.
|
||||
const client = new CloudTasksClient()
|
||||
|
|
@ -65,7 +67,7 @@ const createHttpTaskWithToken = async ({
|
|||
> => {
|
||||
// If there is no Google Cloud Project Id exposed, it means that we are in local environment
|
||||
if (env.dev.isLocal || !project) {
|
||||
console.error(
|
||||
logger.error(
|
||||
'error: attempting to create a cloud task but not running in google cloud.'
|
||||
)
|
||||
return null
|
||||
|
|
@ -112,7 +114,7 @@ const createHttpTaskWithToken = async ({
|
|||
}
|
||||
|
||||
try {
|
||||
return client.createTask({ parent, task })
|
||||
return await client.createTask({ parent, task })
|
||||
} catch (error) {
|
||||
logError(error)
|
||||
return null
|
||||
|
|
@ -170,7 +172,6 @@ export const createAppEngineTask = async ({
|
|||
}
|
||||
|
||||
logger.info('Sending task:')
|
||||
logger.info(task)
|
||||
// Send create task request.
|
||||
const request = { parent: parent, task: task }
|
||||
const [response] = await client.createTask(request)
|
||||
|
|
@ -578,59 +579,29 @@ export const enqueueExportToIntegration = async (
|
|||
return createdTasks[0].name
|
||||
}
|
||||
|
||||
export const enqueueThumbnailTask = async (
|
||||
export const enqueueThumbnailJob = async (
|
||||
userId: string,
|
||||
slug: string
|
||||
): Promise<string> => {
|
||||
const { GOOGLE_CLOUD_PROJECT } = process.env
|
||||
libraryItemId: string
|
||||
) => {
|
||||
const queue = await getBackendQueue()
|
||||
if (!queue) {
|
||||
return undefined
|
||||
}
|
||||
const payload = {
|
||||
userId,
|
||||
slug,
|
||||
libraryItemId,
|
||||
}
|
||||
|
||||
const headers = {
|
||||
Cookie: `auth=${generateVerificationToken({ id: userId })}`,
|
||||
}
|
||||
|
||||
// If there is no Google Cloud Project Id exposed, it means that we are in local environment
|
||||
if (env.dev.isLocal || !GOOGLE_CLOUD_PROJECT) {
|
||||
if (env.queue.thumbnailTaskHandlerUrl) {
|
||||
// Calling the handler function directly.
|
||||
setTimeout(() => {
|
||||
axios
|
||||
.post(env.queue.thumbnailTaskHandlerUrl, payload, {
|
||||
headers,
|
||||
})
|
||||
.catch((error) => {
|
||||
logError(error)
|
||||
})
|
||||
}, 0)
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
const createdTasks = await createHttpTaskWithToken({
|
||||
payload,
|
||||
taskHandlerUrl: env.queue.thumbnailTaskHandlerUrl,
|
||||
requestHeaders: headers,
|
||||
queue: 'omnivore-thumbnail-queue',
|
||||
return queue.add(THUMBNAIL_JOB, payload, {
|
||||
priority: 100,
|
||||
attempts: 1,
|
||||
})
|
||||
|
||||
if (!createdTasks || !createdTasks[0].name) {
|
||||
logger.error(`Unable to get the name of the task`, {
|
||||
payload,
|
||||
createdTasks,
|
||||
})
|
||||
throw new CreateTaskError(`Unable to get the name of the task`)
|
||||
}
|
||||
return createdTasks[0].name
|
||||
}
|
||||
|
||||
export interface RssSubscriptionGroup {
|
||||
url: string
|
||||
subscriptionIds: string[]
|
||||
userIds: string[]
|
||||
fetchedDates: (Date | null)[]
|
||||
mostRecentItemDates: (Date | null)[]
|
||||
scheduledDates: Date[]
|
||||
checksums: (string | null)[]
|
||||
fetchContents: boolean[]
|
||||
|
|
@ -648,7 +619,7 @@ export const enqueueRssFeedFetch = async (
|
|||
},
|
||||
subscriptionIds: subscriptionGroup.subscriptionIds,
|
||||
feedUrl: subscriptionGroup.url,
|
||||
lastFetchedTimestamps: subscriptionGroup.fetchedDates.map(
|
||||
mostRecentItemDates: subscriptionGroup.mostRecentItemDates.map(
|
||||
(timestamp) => timestamp?.getTime() || 0
|
||||
), // unix timestamp in milliseconds
|
||||
lastFetchedChecksums: subscriptionGroup.checksums,
|
||||
|
|
@ -677,4 +648,16 @@ export const enqueueRssFeedFetch = async (
|
|||
}
|
||||
}
|
||||
|
||||
export const enqueueTriggerRuleJob = async (data: TriggerRuleJobData) => {
|
||||
const queue = await getBackendQueue()
|
||||
if (!queue) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return queue.add(TRIGGER_RULE_JOB_NAME, data, {
|
||||
removeOnComplete: true,
|
||||
removeOnFail: true,
|
||||
})
|
||||
}
|
||||
|
||||
export default createHttpTaskWithToken
|
||||
|
|
|
|||
|
|
@ -22,11 +22,9 @@ import {
|
|||
PageType,
|
||||
Profile,
|
||||
Recommendation,
|
||||
ResolverFn,
|
||||
SearchItem,
|
||||
} from '../generated/graphql'
|
||||
import { createPubSubClient } from '../pubsub'
|
||||
import { Claims, WithDataSourcesContext } from '../resolvers/types'
|
||||
import { validateUrl } from '../services/create_page_save_request'
|
||||
import { updateLibraryItem } from '../services/library_item'
|
||||
import { Merge } from '../util'
|
||||
|
|
@ -391,17 +389,10 @@ export const setRecentlySavedItemInRedis = async (
|
|||
url: string
|
||||
) => {
|
||||
// save the url in redis for 26 hours so rss-feeder won't try to re-save it
|
||||
if (!redisClient) {
|
||||
console.info(
|
||||
'not setting recently saved item because redis is not configured'
|
||||
)
|
||||
return
|
||||
}
|
||||
// save the url in redis for 8 hours so rss-feeder won't try to re-save it
|
||||
const redisKey = `recent-saved-item:${userId}:${url}`
|
||||
const ttlInSeconds = 60 * 60 * 26
|
||||
try {
|
||||
return redisClient.set(redisKey, 1, 'EX', ttlInSeconds, 'NX')
|
||||
return await redisClient.set(redisKey, 1, 'EX', ttlInSeconds, 'NX')
|
||||
} catch (error) {
|
||||
logger.error('error setting recently saved item in redis', {
|
||||
redisKey,
|
||||
|
|
|
|||
|
|
@ -34,11 +34,9 @@ export class CustomTypeOrmLogger
|
|||
}
|
||||
|
||||
logQuery(query: string, parameters?: any[], queryRunner?: QueryRunner) {
|
||||
this.logger.info(
|
||||
`query: ${query} -- PARAMETERS: ${super.stringifyParams(
|
||||
parameters || []
|
||||
)}`
|
||||
)
|
||||
this.logger.info(query, {
|
||||
parameters,
|
||||
})
|
||||
}
|
||||
|
||||
log(
|
||||
|
|
@ -133,10 +131,8 @@ const truncateObjectDeep = (object: any, length: number): any => {
|
|||
|
||||
class GcpLoggingTransport extends LoggingWinston {
|
||||
log(info: any, callback: (err: Error | null, apiResponse?: any) => void) {
|
||||
const sizeInfo = jsonStringify(info).length
|
||||
if (sizeInfo > MAX_LOG_SIZE) {
|
||||
info = truncateObjectDeep(info, 500) as never // the max length for string values is 500
|
||||
}
|
||||
// reduce the size of the log entry by truncating any string values to 500 characters
|
||||
info = truncateObjectDeep(info, 500) as never
|
||||
super.log(info, callback)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -223,7 +223,6 @@ const getReadabilityResult = async (
|
|||
export const parsePreparedContent = async (
|
||||
url: string,
|
||||
preparedDocument: PreparedDocumentInput,
|
||||
parseResult?: Readability.ParseResult | null,
|
||||
isNewsletter?: boolean,
|
||||
allowRetry = true
|
||||
): Promise<ParsedContentPuppeteer> => {
|
||||
|
|
@ -232,12 +231,8 @@ export const parsePreparedContent = async (
|
|||
labels: { source: 'parsePreparedContent' },
|
||||
}
|
||||
|
||||
// If we have a parse result, use it
|
||||
let article = parseResult || null
|
||||
let highlightData = undefined
|
||||
const { document, pageInfo } = preparedDocument
|
||||
|
||||
if (!document) {
|
||||
const { document: domContent, pageInfo } = preparedDocument
|
||||
if (!domContent) {
|
||||
logger.info('No document')
|
||||
return {
|
||||
canonicalUrl: url,
|
||||
|
|
@ -257,142 +252,147 @@ export const parsePreparedContent = async (
|
|||
return {
|
||||
canonicalUrl: url,
|
||||
parsedContent: null,
|
||||
domContent: document,
|
||||
domContent,
|
||||
pageType: PageType.Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
let dom: Document | null = null
|
||||
const { title: pageInfoTitle, canonicalUrl } = pageInfo
|
||||
|
||||
let parsedContent: Readability.ParseResult | null = null
|
||||
let pageType = PageType.Unknown
|
||||
let highlightData = undefined
|
||||
|
||||
try {
|
||||
dom = parseHTML(document).document
|
||||
const document = parseHTML(domContent).document
|
||||
pageType = parseOriginalContent(document)
|
||||
|
||||
if (!article) {
|
||||
// Attempt to parse the article
|
||||
// preParse content
|
||||
dom = (await preParseContent(url, dom)) || dom
|
||||
// Run readability
|
||||
await preParseContent(url, document)
|
||||
|
||||
article = await getReadabilityResult(url, document, dom, isNewsletter)
|
||||
}
|
||||
parsedContent = await getReadabilityResult(
|
||||
url,
|
||||
domContent,
|
||||
document,
|
||||
isNewsletter
|
||||
)
|
||||
|
||||
if (!article?.textContent && allowRetry) {
|
||||
const newDocument = {
|
||||
...preparedDocument,
|
||||
document: '<html><body>' + document + '</body></html>', // wrap in body
|
||||
if (!parsedContent || !parsedContent.content) {
|
||||
logger.info('No parsed content')
|
||||
|
||||
if (allowRetry) {
|
||||
logger.info('Retrying with content wrapped in html body')
|
||||
|
||||
const newDocument = {
|
||||
...preparedDocument,
|
||||
document: '<html><body>' + domContent + '</body></html>', // wrap in body
|
||||
}
|
||||
return parsePreparedContent(url, newDocument, isNewsletter, false)
|
||||
}
|
||||
|
||||
return {
|
||||
canonicalUrl,
|
||||
parsedContent,
|
||||
domContent,
|
||||
pageType,
|
||||
}
|
||||
return parsePreparedContent(
|
||||
url,
|
||||
newDocument,
|
||||
parseResult,
|
||||
isNewsletter,
|
||||
false
|
||||
)
|
||||
}
|
||||
|
||||
// use title if not found after running readability
|
||||
if (!parsedContent.title && pageInfoTitle) {
|
||||
parsedContent.title = pageInfoTitle
|
||||
}
|
||||
|
||||
const newDocumentElement = parsedContent.documentElement
|
||||
// Format code blocks
|
||||
// TODO: we probably want to move this type of thing
|
||||
// to the handlers, and have some concept of postHandle
|
||||
if (article?.content) {
|
||||
const articleDom = parseHTML(article.content).document
|
||||
const codeBlocks = articleDom.querySelectorAll(
|
||||
'code, pre[class^="prism-"], pre[class^="language-"]'
|
||||
)
|
||||
if (codeBlocks.length > 0) {
|
||||
codeBlocks.forEach((e) => {
|
||||
if (e.textContent) {
|
||||
const att = hljs.highlightAuto(e.textContent)
|
||||
const code = articleDom.createElement('code')
|
||||
const langClass =
|
||||
`hljs language-${att.language}` +
|
||||
(att.second_best?.language
|
||||
? ` language-${att.second_best?.language}`
|
||||
: '')
|
||||
code.setAttribute('class', langClass)
|
||||
code.innerHTML = att.value
|
||||
e.replaceWith(code)
|
||||
}
|
||||
const codeBlocks = newDocumentElement.querySelectorAll(
|
||||
'pre[class^="prism-"], pre[class^="language-"], code'
|
||||
)
|
||||
codeBlocks.forEach((e) => {
|
||||
if (!e.textContent) {
|
||||
return e.parentNode?.removeChild(e)
|
||||
}
|
||||
|
||||
// replace <br> or <p> or </p> with \n
|
||||
e.innerHTML = e.innerHTML.replace(/<(br|p|\/p)>/g, '\n')
|
||||
|
||||
const att = hljs.highlightAuto(e.textContent)
|
||||
const code = document.createElement('code')
|
||||
const langClass =
|
||||
`hljs language-${att.language}` +
|
||||
(att.second_best?.language
|
||||
? ` language-${att.second_best?.language}`
|
||||
: '')
|
||||
code.setAttribute('class', langClass)
|
||||
code.innerHTML = att.value
|
||||
e.replaceWith(code)
|
||||
})
|
||||
|
||||
highlightData = findEmbeddedHighlight(newDocumentElement)
|
||||
|
||||
const ANCHOR_ELEMENTS_BLOCKED_ATTRIBUTES = [
|
||||
'omnivore-highlight-id',
|
||||
'data-twitter-tweet-id',
|
||||
'data-instagram-id',
|
||||
]
|
||||
|
||||
// Get the top level element?
|
||||
// const pageNode = newDocumentElement.firstElementChild as HTMLElement
|
||||
const nodesToVisitStack: [HTMLElement] = [newDocumentElement]
|
||||
const visitedNodeList = []
|
||||
|
||||
while (nodesToVisitStack.length > 0) {
|
||||
const currentNode = nodesToVisitStack.pop()
|
||||
if (
|
||||
currentNode?.nodeType !== 1 ||
|
||||
// Avoiding dynamic elements from being counted as anchor-allowed elements
|
||||
ANCHOR_ELEMENTS_BLOCKED_ATTRIBUTES.some((attrib) =>
|
||||
currentNode.hasAttribute(attrib)
|
||||
)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
visitedNodeList.push(currentNode)
|
||||
;[].slice
|
||||
.call(currentNode.childNodes)
|
||||
.reverse()
|
||||
.forEach(function (node) {
|
||||
nodesToVisitStack.push(node)
|
||||
})
|
||||
article.content = articleDom.documentElement.outerHTML
|
||||
}
|
||||
|
||||
highlightData = findEmbeddedHighlight(articleDom.documentElement)
|
||||
|
||||
const ANCHOR_ELEMENTS_BLOCKED_ATTRIBUTES = [
|
||||
'omnivore-highlight-id',
|
||||
'data-twitter-tweet-id',
|
||||
'data-instagram-id',
|
||||
]
|
||||
|
||||
// Get the top level element?
|
||||
const pageNode = articleDom.firstElementChild as HTMLElement
|
||||
const nodesToVisitStack: [HTMLElement] = [pageNode]
|
||||
const visitedNodeList = []
|
||||
|
||||
while (nodesToVisitStack.length > 0) {
|
||||
const currentNode = nodesToVisitStack.pop()
|
||||
if (
|
||||
currentNode?.nodeType !== 1 ||
|
||||
// Avoiding dynamic elements from being counted as anchor-allowed elements
|
||||
ANCHOR_ELEMENTS_BLOCKED_ATTRIBUTES.some((attrib) =>
|
||||
currentNode.hasAttribute(attrib)
|
||||
)
|
||||
) {
|
||||
continue
|
||||
}
|
||||
visitedNodeList.push(currentNode)
|
||||
;[].slice
|
||||
.call(currentNode.childNodes)
|
||||
.reverse()
|
||||
.forEach(function (node) {
|
||||
nodesToVisitStack.push(node)
|
||||
})
|
||||
}
|
||||
|
||||
visitedNodeList.shift()
|
||||
visitedNodeList.forEach((node, index) => {
|
||||
// start from index 1, index 0 reserved for anchor unknown.
|
||||
node.setAttribute('data-omnivore-anchor-idx', (index + 1).toString())
|
||||
})
|
||||
|
||||
article.content = articleDom.documentElement.outerHTML
|
||||
}
|
||||
|
||||
visitedNodeList.shift()
|
||||
visitedNodeList.forEach((node, index) => {
|
||||
// start from index 1, index 0 reserved for anchor unknown.
|
||||
node.setAttribute('data-omnivore-anchor-idx', (index + 1).toString())
|
||||
})
|
||||
|
||||
const newHtml = newDocumentElement.outerHTML
|
||||
const newWindow = parseHTML('')
|
||||
const DOMPurify = createDOMPurify(newWindow)
|
||||
DOMPurify.addHook('uponSanitizeElement', domPurifySanitizeHook)
|
||||
const clean = DOMPurify.sanitize(article?.content || '', DOM_PURIFY_CONFIG)
|
||||
const cleanHtml = DOMPurify.sanitize(newHtml, DOM_PURIFY_CONFIG)
|
||||
parsedContent.content = cleanHtml
|
||||
|
||||
Object.assign(article || {}, {
|
||||
content: clean,
|
||||
title: article?.title,
|
||||
previewImage: article?.previewImage,
|
||||
siteName: article?.siteName,
|
||||
siteIcon: article?.siteIcon,
|
||||
byline: article?.byline,
|
||||
language: article?.language,
|
||||
})
|
||||
logRecord.parseSuccess = true
|
||||
} catch (error) {
|
||||
logger.info('Error parsing content', error)
|
||||
logger.error('Error parsing content', error)
|
||||
|
||||
Object.assign(logRecord, {
|
||||
parseSuccess: false,
|
||||
parseError: error,
|
||||
})
|
||||
}
|
||||
|
||||
const { title, canonicalUrl } = pageInfo
|
||||
|
||||
Object.assign(article || {}, {
|
||||
title: article?.title || title,
|
||||
})
|
||||
|
||||
logger.info('parse-article completed')
|
||||
logger.info('parse-article completed', logRecord)
|
||||
|
||||
return {
|
||||
domContent: document,
|
||||
parsedContent: article,
|
||||
canonicalUrl,
|
||||
pageType: dom ? parseOriginalContent(dom) : PageType.Unknown,
|
||||
parsedContent,
|
||||
domContent,
|
||||
pageType,
|
||||
highlightData,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ export const sendMulticastPushNotifications = async (
|
|||
})
|
||||
|
||||
logger.info('sending multicast message: ', message)
|
||||
const res = await getMessaging().sendMulticast(message)
|
||||
const res = await getMessaging().sendEachForMulticast(message)
|
||||
logger.info('send notification result: ', res.responses)
|
||||
|
||||
return res
|
||||
|
|
@ -75,7 +75,7 @@ export const sendBatchPushNotifications = async (
|
|||
messages: Message[]
|
||||
): Promise<BatchResponse | undefined> => {
|
||||
try {
|
||||
const res = await getMessaging().sendAll(messages)
|
||||
const res = await getMessaging().sendEach(messages)
|
||||
logger.info(`success count: ${res.successCount}`)
|
||||
|
||||
return res
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ export const mochaGlobalSetup = async () => {
|
|||
await createTestConnection()
|
||||
console.log('db connection created')
|
||||
|
||||
if (env.redis.url) {
|
||||
if (env.redis.cache.url) {
|
||||
await redisDataSource.initialize()
|
||||
console.log('redis connection created')
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ export const mochaGlobalTeardown = async () => {
|
|||
await appDataSource.destroy()
|
||||
console.log('db connection closed')
|
||||
|
||||
if (env.redis.url) {
|
||||
if (env.redis.cache.url) {
|
||||
await redisDataSource.shutdown()
|
||||
console.log('redis connection closed')
|
||||
}
|
||||
|
|
|
|||
|
|
@ -218,14 +218,18 @@ const savePageQuery = (
|
|||
`
|
||||
}
|
||||
|
||||
const saveFileQuery = (url: string, uploadFileId: string) => {
|
||||
const saveFileQuery = (
|
||||
clientRequestId: string,
|
||||
url: string,
|
||||
uploadFileId: string
|
||||
) => {
|
||||
return `
|
||||
mutation {
|
||||
saveFile (
|
||||
input: {
|
||||
url: "${url}",
|
||||
source: "test",
|
||||
clientRequestId: "${generateFakeUuid()}",
|
||||
clientRequestId: "${clientRequestId}",
|
||||
uploadFileId: "${uploadFileId}",
|
||||
}
|
||||
) {
|
||||
|
|
@ -832,8 +836,23 @@ describe('Article API', () => {
|
|||
let query = ''
|
||||
let url = ''
|
||||
let uploadFileId = ''
|
||||
let itemId = ''
|
||||
|
||||
before(async () => {
|
||||
const item = await createLibraryItem(
|
||||
{
|
||||
user: { id: user.id },
|
||||
originalUrl: 'https://blog.omnivore.app/setBookmarkArticle',
|
||||
slug: 'test-with-omnivore',
|
||||
readableContent: '<p>test</p>',
|
||||
title: 'test title',
|
||||
readingProgressBottomPercent: 100,
|
||||
readingProgressTopPercent: 80,
|
||||
},
|
||||
user.id
|
||||
)
|
||||
itemId = item.id
|
||||
|
||||
before(() => {
|
||||
sinon.replace(
|
||||
uploads,
|
||||
'getStorageFileDetails',
|
||||
|
|
@ -842,7 +861,7 @@ describe('Article API', () => {
|
|||
})
|
||||
|
||||
beforeEach(() => {
|
||||
query = saveFileQuery(url, uploadFileId)
|
||||
query = saveFileQuery(itemId, url, uploadFileId)
|
||||
})
|
||||
|
||||
after(() => {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,12 @@
|
|||
import Redis, { RedisOptions } from 'ioredis'
|
||||
|
||||
type RedisClientType = 'cache' | 'mq'
|
||||
type RedisDataSourceOption = {
|
||||
url?: string
|
||||
cert?: string
|
||||
}
|
||||
export type RedisDataSourceOptions = {
|
||||
REDIS_URL?: string
|
||||
REDIS_CERT?: string
|
||||
[key in RedisClientType]: RedisDataSourceOption
|
||||
}
|
||||
|
||||
export class RedisDataSource {
|
||||
|
|
@ -14,12 +18,12 @@ export class RedisDataSource {
|
|||
constructor(options: RedisDataSourceOptions) {
|
||||
this.options = options
|
||||
|
||||
this.cacheClient = createRedisClient('cache', this.options)
|
||||
this.queueRedisClient = createRedisClient('queue', this.options)
|
||||
}
|
||||
const cacheClient = createIORedisClient('cache', this.options)
|
||||
if (!cacheClient) throw 'Error initializing cache redis client'
|
||||
|
||||
setOptions(options: RedisDataSourceOptions): void {
|
||||
this.options = options
|
||||
this.cacheClient = cacheClient
|
||||
this.queueRedisClient =
|
||||
createIORedisClient('mq', this.options) || this.cacheClient // if mq is not defined, use cache
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
|
|
@ -32,46 +36,45 @@ export class RedisDataSource {
|
|||
}
|
||||
}
|
||||
|
||||
const createRedisClient = (name: string, options: RedisDataSourceOptions) => {
|
||||
const redisURL = options.REDIS_URL
|
||||
const cert = options.REDIS_CERT?.replace(/\\n/g, '\n') // replace \n with new line
|
||||
const createIORedisClient = (
|
||||
name: RedisClientType,
|
||||
options: RedisDataSourceOptions
|
||||
): Redis | undefined => {
|
||||
const option = options[name]
|
||||
const redisURL = option.url
|
||||
if (!redisURL) {
|
||||
throw 'Error: no redisURL supplied'
|
||||
console.log(`no redisURL supplied: ${name}`)
|
||||
return undefined
|
||||
}
|
||||
|
||||
const redisOptions: RedisOptions = {
|
||||
name,
|
||||
connectTimeout: 10000, // 10 seconds
|
||||
tls: cert
|
||||
const redisCert = option.cert
|
||||
const tls =
|
||||
redisURL.startsWith('rediss://') && redisCert
|
||||
? {
|
||||
cert,
|
||||
rejectUnauthorized: false, // for self-signed certs
|
||||
ca: redisCert,
|
||||
rejectUnauthorized: false,
|
||||
}
|
||||
: undefined,
|
||||
: undefined
|
||||
|
||||
const redisOptions: RedisOptions = {
|
||||
tls,
|
||||
name,
|
||||
connectTimeout: 10000,
|
||||
maxRetriesPerRequest: null,
|
||||
offlineQueue: false,
|
||||
}
|
||||
|
||||
const redis = new Redis(redisURL, redisOptions)
|
||||
|
||||
redis.on('connect', () => {
|
||||
console.log('Redis connected', name)
|
||||
})
|
||||
|
||||
redis.on('error', (err) => {
|
||||
console.error('Redis error', err, name)
|
||||
})
|
||||
|
||||
redis.on('close', () => {
|
||||
console.log('Redis closed', name)
|
||||
})
|
||||
|
||||
return redis
|
||||
return new Redis(redisURL, redisOptions)
|
||||
}
|
||||
|
||||
export const redisDataSource = new RedisDataSource({
|
||||
REDIS_URL: process.env.REDIS_URL,
|
||||
REDIS_CERT: process.env.REDIS_CERT,
|
||||
cache: {
|
||||
url: process.env.REDIS_URL,
|
||||
cert: process.env.REDIS_CERT,
|
||||
},
|
||||
mq: {
|
||||
url: process.env.MQ_REDIS_URL,
|
||||
cert: process.env.MQ_REDIS_CERT,
|
||||
},
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
|
|
|
|||
|
|
@ -50,12 +50,11 @@ interface FetchResult {
|
|||
title?: string
|
||||
content?: string
|
||||
contentType?: string
|
||||
readabilityResult?: unknown
|
||||
}
|
||||
|
||||
export const cacheFetchResult = async (fetchResult: FetchResult) => {
|
||||
// cache the fetch result for 4 hours
|
||||
const ttl = 4 * 60 * 60
|
||||
// cache the fetch result for 24 hours
|
||||
const ttl = 24 * 60 * 60
|
||||
const key = `fetch-result:${fetchResult.finalUrl}`
|
||||
const value = JSON.stringify(fetchResult)
|
||||
return redisDataSource.cacheClient.set(key, value, 'EX', ttl, 'NX')
|
||||
|
|
@ -69,7 +68,6 @@ export const contentFetchRequestHandler: RequestHandler = async (req, res) => {
|
|||
// users is used when saving article for multiple users
|
||||
let users = body.users || []
|
||||
const userId = body.userId
|
||||
const folder = body.folder
|
||||
// userId is used when saving article for a single user
|
||||
if (userId) {
|
||||
users = [
|
||||
|
|
@ -105,7 +103,6 @@ export const contentFetchRequestHandler: RequestHandler = async (req, res) => {
|
|||
rssFeedUrl,
|
||||
savedAt,
|
||||
publishedAt,
|
||||
folder,
|
||||
users,
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ export const createRedisClient = (url?: string, cert?: string) => {
|
|||
connectTimeout: 10000, // 10 seconds
|
||||
tls: cert
|
||||
? {
|
||||
cert,
|
||||
cert: cert.replace(/\\n/g, '\n'), // replace \n with new line
|
||||
rejectUnauthorized: false, // for self-signed certs
|
||||
}
|
||||
: undefined,
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ interface Tweet {
|
|||
export class NitterHandler extends ContentHandler {
|
||||
// matches twitter.com and nitter.net urls
|
||||
URL_MATCH =
|
||||
/((twitter\.com)|(nitter\.net))\/(?:#!\/)?(\w+)\/status(?:es)?\/(\d+)(?:\/.*)?/
|
||||
/((x\.com)|(twitter\.com)|(nitter\.net))\/(?:#!\/)?(\w+)\/status(?:es)?\/(\d+)(?:\/.*)?/
|
||||
INSTANCES = [
|
||||
{ value: 'https://nitter.moomoo.me', score: 0 },
|
||||
{ value: 'https://nitter.net', score: 1 }, // the official instance
|
||||
|
|
@ -316,7 +316,7 @@ export class NitterHandler extends ContentHandler {
|
|||
parseTweetUrl = (url: string) => {
|
||||
const match = url.match(this.URL_MATCH)
|
||||
return {
|
||||
domain: match?.[1],
|
||||
domain: match?.[1]?.replace('x', 'twitter'),
|
||||
username: match?.[4],
|
||||
tweetId: match?.[5],
|
||||
}
|
||||
|
|
|
|||
17
packages/db/migrations/0159.do.alter_subscriptions.sql
Executable file
17
packages/db/migrations/0159.do.alter_subscriptions.sql
Executable file
|
|
@ -0,0 +1,17 @@
|
|||
-- Type: DO
|
||||
-- Name: alter_subscriptions
|
||||
-- Description: Alter omnivore.subscriptions table to add a new state and date column
|
||||
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE omnivore.subscriptions
|
||||
ADD COLUMN failed_at timestamptz,
|
||||
ADD COLUMN refreshed_at timestamptz;
|
||||
UPDATE omnivore.subscriptions
|
||||
SET refreshed_at = last_fetched_at
|
||||
WHERE last_fetched_at IS NOT NULL;
|
||||
|
||||
ALTER TABLE omnivore.subscriptions
|
||||
RENAME COLUMN last_fetched_at TO most_recent_item_date;
|
||||
|
||||
COMMIT;
|
||||
14
packages/db/migrations/0159.undo.alter_subscriptions.sql
Executable file
14
packages/db/migrations/0159.undo.alter_subscriptions.sql
Executable file
|
|
@ -0,0 +1,14 @@
|
|||
-- Type: UNDO
|
||||
-- Name: alter_subscriptions
|
||||
-- Description: Alter omnivore.subscriptions table to add a new state and date column
|
||||
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE omnivore.subscriptions
|
||||
RENAME COLUMN most_recent_item_date TO last_fetched_at;
|
||||
|
||||
ALTER TABLE omnivore.subscriptions
|
||||
DROP COLUMN failed_at,
|
||||
DROP COLUMN refreshed_at;
|
||||
|
||||
COMMIT;
|
||||
|
|
@ -117,8 +117,6 @@ export const inboundEmailHandler = Sentry.GCPFunction.wrapHttpFunction(
|
|||
}
|
||||
}
|
||||
const headers = parseHeaders(parsed.headers)
|
||||
console.log('parsed: ', parsed)
|
||||
console.log('headers: ', headers)
|
||||
|
||||
// original sender email address
|
||||
const from = parsed['from']
|
||||
|
|
|
|||
|
|
@ -1,10 +1,7 @@
|
|||
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
||||
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
|
||||
import { preHandleContent, preParseContent } from '@omnivore/content-handler'
|
||||
import { Readability } from '@omnivore/readability'
|
||||
import { preHandleContent } from '@omnivore/content-handler'
|
||||
import axios from 'axios'
|
||||
import crypto from 'crypto'
|
||||
import createDOMPurify, { SanitizeElementHookEvent } from 'dompurify'
|
||||
// const { Storage } = require('@google-cloud/storage');
|
||||
import { parseHTML } from 'linkedom'
|
||||
import path from 'path'
|
||||
|
|
@ -13,7 +10,6 @@ import puppeteer from 'puppeteer-extra'
|
|||
import AdblockerPlugin from 'puppeteer-extra-plugin-adblocker'
|
||||
import StealthPlugin from 'puppeteer-extra-plugin-stealth'
|
||||
import Url from 'url'
|
||||
import { encode } from 'urlsafe-base64'
|
||||
|
||||
// Add stealth plugin to hide puppeteer usage
|
||||
puppeteer.use(StealthPlugin())
|
||||
|
|
@ -28,12 +24,12 @@ puppeteer.use(AdblockerPlugin({ blockTrackers: true }))
|
|||
|
||||
// const filePath = `${os.tmpdir()}/previewImage.png`
|
||||
|
||||
const MOBILE_USER_AGENT =
|
||||
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.62 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
|
||||
// const MOBILE_USER_AGENT =
|
||||
// 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.62 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
|
||||
const DESKTOP_USER_AGENT =
|
||||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_6_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4372.0 Safari/537.36'
|
||||
const BOT_DESKTOP_USER_AGENT =
|
||||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_6_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4372.0 Safari/537.36'
|
||||
// const BOT_DESKTOP_USER_AGENT =
|
||||
// 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_6_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4372.0 Safari/537.36'
|
||||
const NON_BOT_DESKTOP_USER_AGENT =
|
||||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_6_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4372.0 Safari/537.36'
|
||||
const NON_BOT_HOSTS = ['bloomberg.com', 'forbes.com']
|
||||
|
|
@ -156,8 +152,8 @@ export const fetchContent = async (
|
|||
page: Page | undefined,
|
||||
title: string | undefined,
|
||||
content: string | undefined,
|
||||
contentType: string | undefined,
|
||||
readabilityResult: Readability.ParseResult | null | undefined
|
||||
contentType: string | undefined
|
||||
|
||||
try {
|
||||
url = getUrl(url)
|
||||
if (!url) {
|
||||
|
|
@ -230,34 +226,26 @@ export const fetchContent = async (
|
|||
console.info('fallback to scrapingbee', url)
|
||||
|
||||
const sbResult = await fetchContentWithScrapingBee(url)
|
||||
content = sbResult.domContent
|
||||
title = sbResult.title
|
||||
} else {
|
||||
throw e
|
||||
|
||||
return {
|
||||
finalUrl: url,
|
||||
title: sbResult.title,
|
||||
content: sbResult.domContent,
|
||||
contentType,
|
||||
}
|
||||
}
|
||||
|
||||
throw e
|
||||
} finally {
|
||||
// close browser context if it was opened
|
||||
if (context) {
|
||||
await context.close()
|
||||
}
|
||||
// save non pdf content
|
||||
if (url && contentType !== 'application/pdf') {
|
||||
// parse content if it is not empty
|
||||
if (content) {
|
||||
let document = parseHTML(content).document
|
||||
// preParse content
|
||||
const preParsedDom = await preParseContent(url, document)
|
||||
if (preParsedDom) {
|
||||
document = preParsedDom
|
||||
}
|
||||
readabilityResult = await getReadabilityResult(url, document)
|
||||
}
|
||||
}
|
||||
|
||||
console.info(`content-fetch result`, logRecord)
|
||||
}
|
||||
|
||||
return { finalUrl: url, title, content, readabilityResult, contentType }
|
||||
return { finalUrl: url, title, content, contentType }
|
||||
}
|
||||
|
||||
function validateUrlString(url: string) {
|
||||
|
|
@ -741,99 +729,3 @@ async function retrieveHtml(page: Page, logRecord: Record<string, any>) {
|
|||
// console.info(`preview-image`, logRecord);
|
||||
// return res.redirect(`${process.env.PREVIEW_IMAGE_CDN_ORIGIN}/${destination}`);
|
||||
// }
|
||||
|
||||
const DOM_PURIFY_CONFIG = {
|
||||
ADD_TAGS: ['iframe'],
|
||||
ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling'],
|
||||
FORBID_ATTR: [
|
||||
'data-ml-dynamic',
|
||||
'data-ml-dynamic-type',
|
||||
'data-orig-url',
|
||||
'data-ml-id',
|
||||
'data-ml',
|
||||
'data-xid',
|
||||
'data-feature',
|
||||
],
|
||||
}
|
||||
|
||||
function domPurifySanitizeHook(node: Element, data: SanitizeElementHookEvent) {
|
||||
if (data.tagName === 'iframe') {
|
||||
const urlRegex = /^(https?:)?\/\/www\.youtube(-nocookie)?\.com\/embed\//i
|
||||
const src = node.getAttribute('src') || ''
|
||||
const dataSrc = node.getAttribute('data-src') || ''
|
||||
|
||||
if (src && urlRegex.test(src)) {
|
||||
return
|
||||
}
|
||||
|
||||
if (dataSrc && urlRegex.test(dataSrc)) {
|
||||
node.setAttribute('src', dataSrc)
|
||||
return
|
||||
}
|
||||
|
||||
node.parentNode?.removeChild(node)
|
||||
}
|
||||
}
|
||||
|
||||
function getPurifiedContent(html: Document) {
|
||||
const newWindow = parseHTML('')
|
||||
const DOMPurify = createDOMPurify(newWindow)
|
||||
DOMPurify.addHook('uponSanitizeElement', domPurifySanitizeHook)
|
||||
const clean = DOMPurify.sanitize(html, DOM_PURIFY_CONFIG)
|
||||
return parseHTML(clean).document
|
||||
}
|
||||
|
||||
function signImageProxyUrl(url: string) {
|
||||
return encode(
|
||||
crypto
|
||||
.createHmac('sha256', process.env.IMAGE_PROXY_SECRET || '')
|
||||
.update(url)
|
||||
.digest()
|
||||
)
|
||||
}
|
||||
|
||||
function createImageProxyUrl(url: string, width = 0, height = 0) {
|
||||
if (!process.env.IMAGE_PROXY_URL || !process.env.IMAGE_PROXY_SECRET) {
|
||||
return url
|
||||
}
|
||||
|
||||
const urlWithOptions = `${url}#${width}x${height}`
|
||||
const signature = signImageProxyUrl(urlWithOptions)
|
||||
|
||||
return `${process.env.IMAGE_PROXY_URL}/${width}x${height},s${signature}/${url}`
|
||||
}
|
||||
|
||||
async function getReadabilityResult(url: string, document: Document) {
|
||||
// First attempt to read the article as is.
|
||||
// if that fails attempt to purify then read
|
||||
const sources = [
|
||||
() => {
|
||||
return document
|
||||
},
|
||||
() => {
|
||||
return getPurifiedContent(document)
|
||||
},
|
||||
]
|
||||
|
||||
for (const source of sources) {
|
||||
const document = source()
|
||||
if (!document) {
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
const article = await new Readability(document, {
|
||||
createImageProxyUrl,
|
||||
url,
|
||||
}).parse()
|
||||
|
||||
if (article) {
|
||||
return article
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('parsing error for url', url, error)
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
|
|
|||
|
|
@ -206,7 +206,7 @@ Readability.prototype = {
|
|||
unlikelyCandidates: /\bad\b|ai2html|banner|breadcrumbs|breadcrumb|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager(?!ow)|popup|yom-remote|copyright|keywords|outline|infinite-list|beta|recirculation|site-index|hide-for-print|post-end-share-cta|post-end-cta-full|post-footer|post-head|post-tag|li-date|main-navigation|programtic-ads|outstream_article|hfeed|comment-holder|back-to-top|show-up-next|onward-journey|topic-tracker|list-nav|block-ad-entity|adSpecs|gift-article-button|modal-title|in-story-masthead|share-tools|standard-dock|expanded-dock|margins-h|subscribe-dialog|icon|bumped|dvz-social-media-buttons|post-toc|mobile-menu|mobile-navbar|tl_article_header|mvp(-post)*-(add-story|soc(-mob)*-wrap)|w-condition-invisible|rich-text-block main w-richtext|rich-text-block_ataglance at-a-glance test w-richtext|PostsPage-commentsSection|hide-text/i,
|
||||
// okMaybeItsACandidate: /and|article(?!-breadcrumb)|body|column|content|main|shadow|post-header/i,
|
||||
get okMaybeItsACandidate() {
|
||||
return new RegExp(`and|(?<!${this.articleNegativeLookAheadCandidates.source})article(?!-(${this.articleNegativeLookBehindCandidates.source}))|body|column|content|^(?!main-navigation|main-header)main|shadow|post-header|hfeed site|blog-posts hfeed|container-banners|menu-opacity|header-with-anchor-widget|commentOnSelection`, 'i')
|
||||
return new RegExp(`and|(?<!${this.articleNegativeLookAheadCandidates.source})article(?!-(${this.articleNegativeLookBehindCandidates.source}))|body|column|content|^(?!main-navigation|main-header)main|shadow|post-header|hfeed site|blog-posts hfeed|container-banners|menu-opacity|header-with-anchor-widget|commentOnSelection|highlight--with-header`, 'i')
|
||||
},
|
||||
|
||||
positive: /article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story|tweet(-\w+)?|instagram|image|container-banners|player|commentOnSelection/i,
|
||||
|
|
@ -261,7 +261,7 @@ Readability.prototype = {
|
|||
"SUP", "TEXTAREA", "TIME", "VAR", "WBR"
|
||||
],
|
||||
|
||||
// These are the classes that readability sets itself.
|
||||
// These are the classes that we want to keep.
|
||||
CLASSES_TO_PRESERVE: [
|
||||
"page", "twitter-tweet", "tweet-placeholder", "instagram-placeholder", "morning-brew-markets", "prism-code"
|
||||
],
|
||||
|
|
@ -3036,16 +3036,16 @@ Readability.prototype = {
|
|||
|
||||
// detect language from the html content
|
||||
const languages = (await cld.detect(content, { isHTML: true })).languages;
|
||||
console.log('Detected languages: ', languages);
|
||||
this.log('Detected languages: ', languages);
|
||||
if (languages.length > 0) {
|
||||
code = languages[0].code;
|
||||
}
|
||||
|
||||
console.log('Getting language name from code: ', code);
|
||||
this.log('Getting language name from code: ', code);
|
||||
let lang = new Intl.DisplayNames(['en'], {type: 'language'});
|
||||
return lang.of(code);
|
||||
} catch (error) {
|
||||
console.error('Failed to get language', error);
|
||||
this.log('Failed to get language', error);
|
||||
return 'English';
|
||||
}
|
||||
},
|
||||
|
|
@ -3135,6 +3135,7 @@ Readability.prototype = {
|
|||
previewImage: metadata.previewImage,
|
||||
publishedDate,
|
||||
language,
|
||||
documentElement: articleContent,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -80,6 +80,12 @@
|
|||
<a href="./test-pages/github-blog/distiller.html" target="iframe_b">[dom-distiller]</a>
|
||||
</li>
|
||||
|
||||
<li>realpython<br />
|
||||
<a href="./test-pages/realpython/source.html" target="iframe_b">[source]</a>
|
||||
<a href="./test-pages/realpython/expected.html" target="iframe_b">[readability]</a>
|
||||
<a href="./test-pages/realpython/distiller.html" target="iframe_b">[dom-distiller]</a>
|
||||
</li>
|
||||
|
||||
<li>josephg<br />
|
||||
<a href="./test-pages/josephg/source.html" target="iframe_b">[source]</a>
|
||||
<a href="./test-pages/josephg/expected.html" target="iframe_b">[readability]</a>
|
||||
|
|
|
|||
932
packages/readabilityjs/test/test-pages/realpython/distiller.html
Normal file
932
packages/readabilityjs/test/test-pages/realpython/distiller.html
Normal file
|
|
@ -0,0 +1,932 @@
|
|||
<div><figure><img alt="Python 3.10: Cool New Features for You to Try" src="https://files.realpython.com/media/Python-3.10-Cool-New-Features-for-You-to-Try_Watermarked.e2782d8a16dc.jpg" srcset="/cdn-cgi/image/width=480,format=auto/https://files.realpython.com/media/Python-3.10-Cool-New-Features-for-You-to-Try_Watermarked.e2782d8a16dc.jpg 480w, /cdn-cgi/image/width=640,format=auto/https://files.realpython.com/media/Python-3.10-Cool-New-Features-for-You-to-Try_Watermarked.e2782d8a16dc.jpg 640w, /cdn-cgi/image/width=960,format=auto/https://files.realpython.com/media/Python-3.10-Cool-New-Features-for-You-to-Try_Watermarked.e2782d8a16dc.jpg 960w, /cdn-cgi/image/width=1920,format=auto/https://files.realpython.com/media/Python-3.10-Cool-New-Features-for-You-to-Try_Watermarked.e2782d8a16dc.jpg 1920w" sizes="(min-width: 1200px) 690px, (min-width: 780px) calc(-5vw + 669px), (min-width: 580px) 510px, calc(100vw - 30px)"/></figure><p>
|
||||
<span> Watch Now</span> This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: <a href="/courses/cool-new-features-python-310/"><strong>Cool New Features in Python 3.10</strong></a>
|
||||
</p><p>
|
||||
<a href="https://www.python.org/downloads/release/python-3100/">Python 3.10 is out!</a> Volunteers have been working on the new version since May 2020 to bring you a better, faster, and more secure Python. As of <a href="https://www.python.org/dev/peps/pep-0619/">October 4, 2021</a>, the first official version is available.
|
||||
</p><p>
|
||||
Each new version of Python brings a host of changes. You can read about all of them in the <a href="https://docs.python.org/3.10/whatsnew/3.10.html">documentation</a>. Here, you’ll get to learn about the coolest new features.
|
||||
</p><p>
|
||||
<strong>In this tutorial, you’ll learn about:</strong>
|
||||
</p><ul><li>Debugging with more helpful and precise <strong>error messages</strong></li><li>Using <strong>structural pattern matching</strong> to work with data structures</li><li>Adding more readable and more specific <strong>type hints</strong></li><li>Checking the <strong>length of sequences</strong> when using <code>zip()</code></li><li>Calculating <strong>multivariable statistics</strong></li></ul><p>
|
||||
To try out the new features yourself, you need to run Python 3.10. You can get it from the <a href="https://www.python.org/downloads/">Python homepage</a>. Alternatively, you can <a href="https://realpython.com/python-versions-docker/">use Docker</a> with the <a href="https://hub.docker.com/_/python/">latest Python image</a>.
|
||||
</p><h2>
|
||||
Better Error Messages
|
||||
</h2><p>
|
||||
Python is often lauded for being a user-friendly programming language. While this is true, there are certain parts of Python that could be friendlier. Python 3.10 comes with a host of more precise and constructive error messages. In this section, you’ll see some of the newest improvements. The full list is available in the <a href="https://docs.python.org/3.10/whatsnew/3.10.html#better-error-messages">documentation</a>.
|
||||
</p><p>
|
||||
Think back to writing your first <a href="https://www.scriptol.com/programming/hello-world.php">Hello World</a> program in Python:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Maybe you created a file, added the famous call to <code>print()</code>, and saved it as <code>hello.py</code>. You then ran the program, eager to call yourself a proper Pythonista. However, something went wrong:
|
||||
</p><div>
|
||||
<span>Shell</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
There was a <code>SyntaxError</code> in the code. <code>EOL</code>, what does that even mean? You went back to your code, and after a bit of staring and searching, you realized that there was a missing quotation mark at the end of your string.
|
||||
</p><p>
|
||||
One of the more impactful improvements in Python 3.10 is better and more precise error messages for many common issues. If you run your buggy Hello World in Python 3.10, you’ll get a bit more help than in earlier versions of Python:
|
||||
</p><div>
|
||||
<span>Shell</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The error message is still a bit technical, but gone is the mysterious <code>EOL</code>. Instead, the message tells you that you need to terminate your string! There are similar improvements to many different error messages, as you’ll see below.
|
||||
</p><p>
|
||||
A <a href="https://realpython.com/invalid-syntax-python/"><code>SyntaxError</code></a> is an error raised when your code is parsed, before it even starts to execute. Syntax errors can be tricky to debug because the interpreter provides imprecise or sometimes even misleading error messages. The following code is missing a curly brace to terminate the dictionary:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The missing closing curly brace that should have been on line 7 is an error. If you run this code with Python 3.9 or earlier, you’ll see the following error message:
|
||||
</p><div>
|
||||
<span>Python Traceback</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The error message highlights line 8, but there are no syntactical problems in line 8! If you’ve experienced your share of syntax errors in Python, you might already know that the trick is to look at the lines <em>before</em> the one Python complains about. In this case, you’re looking for the missing closing brace on line 7.
|
||||
</p><p>
|
||||
In Python 3.10, the same code shows a much more helpful and precise error message:
|
||||
</p><div>
|
||||
<span>Python Traceback</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
This points you straight to the offending dictionary and allows you to fix the issue in no time.
|
||||
</p><p>
|
||||
There are a few other ways to mess up dictionary syntax. A typical one is forgetting a comma after one of the items:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
In this code, a comma is missing at the end of line 4. Python 3.10 gives you a clear suggestion on how to fix your code:
|
||||
</p><div>
|
||||
<span>Python Traceback</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
You can add the missing comma and have your code back up and running in no time.
|
||||
</p><p>
|
||||
Another common mistake is using the <a href="https://realpython.com/python-assignment-operator/">assignment operator</a> (<code>=</code>) instead of the equality comparison operator (<code>==</code>) when you’re comparing values. Previously, this would just cause another <code>invalid syntax</code> message. In the newest version of Python, you get some more advice:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The parser suggests that you maybe meant to use a <a href="https://realpython.com/python-operators-expressions/#comparison-operators">comparison operator</a> or an <a href="https://realpython.com/python-walrus-operator/">assignment expression operator</a> instead.
|
||||
</p><p>
|
||||
Take note of another nifty improvement in Python 3.10 error messages. The last two examples show how carets (<code>^^^</code>) highlight the whole offending expression. Previously, a single caret symbol (<code>^</code>) indicated just an approximate location.
|
||||
</p><p>
|
||||
The final error message improvement that you’ll play with for now is that attribute and name errors can now offer suggestions if you misspell an attribute or a name:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Note that the suggestions work for both built-in names and names that you define yourself, although they may <a href="https://docs.python.org/3.10/whatsnew/3.10.html#attributeerrors">not be available</a> in all environments. If you like these kinds of suggestions, check out <a href="https://github.com/SylvainDe/DidYouMean-Python">BetterErrorMessages</a>, which offers similar suggestions in even more contexts.
|
||||
</p><p>
|
||||
The improvements you’ve seen in this section are just some of the <a href="https://docs.python.org/3.10/whatsnew/3.10.html#better-error-messages">many error messages</a> that have gotten a face-lift. The new Python will be even more user-friendly than before, and hopefully, the new error messages will save you both time and frustration going forward.
|
||||
</p><img src="https://img.realpython.net/f1ef724573f8d74cc59cd07ea9e20a6b"/><h2>
|
||||
Structural Pattern Matching
|
||||
</h2><p>
|
||||
The biggest new feature in Python 3.10, probably both in terms of <a href="https://lwn.net/Articles/845480/">controversy</a> and <a href="https://en.wikipedia.org/wiki/Pattern_matching">potential impact</a>, is <strong>structural pattern matching</strong>. Its introduction has sometimes been referred to as <code>switch ... case</code> coming to Python, but you’ll see that structural pattern matching is much more powerful than that.
|
||||
</p><p>
|
||||
You’ll see three different examples that together highlight why this feature is called structural pattern matching and show you how you can use this new feature:
|
||||
</p><ol><li>Detecting and deconstructing different <strong>structures</strong> in your data</li><li>Using different kinds of <strong>patterns</strong></li><li><strong>Matching</strong> literal patterns</li></ol><p>
|
||||
Structural pattern matching is a comprehensive addition to the Python language. To give you a taste of how you can take advantage of it in your own projects, the next three subsections will dive into some of the details. You’ll also see some links that can help you explore in even more depth if you want.
|
||||
</p><h3>
|
||||
Deconstructing Data Structures
|
||||
</h3><p>
|
||||
At its core, structural pattern matching is about defining patterns to which your data structures can be matched. In this section, you’ll study a practical example where you’ll work with data that are structured differently, even though the meaning is the same. You’ll define several patterns, and depending on which pattern matches your data, you’ll process your data appropriately.
|
||||
</p><p>
|
||||
This section will be a bit light on explanations of the possible patterns. Instead, it will try to give you an impression of the possibilities. The next section will step back and explain the patterns in more detail.
|
||||
</p><p>
|
||||
Time to match your first pattern! The following example uses a <code>match ... case</code> block to find the first name of a user by extracting it from a <code>user</code> data structure:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
You can see structural pattern matching at work in the highlighted lines. <code>user</code> is a small dictionary with user information. The <code>case</code> line specifies a pattern that <code>user</code> is matched against. In this case, you’re looking for a dictionary with a <code>"name"</code> key whose value is a new dictionary. This nested dictionary has a key called <code>"first"</code>. The corresponding value is bound to the variable <code>first_name</code>.
|
||||
</p><p>
|
||||
For a practical example, say that you’re processing user data where the underlying data model changes over time. Therefore, you need to be able to process different versions of the same data.
|
||||
</p><p>
|
||||
In the next example, you’ll use data from <a href="https://randomuser.me">randomuser.me</a>. This is a great API for generating random user data that you can use during testing and development. The API is also an example of an API that has changed over time. You can still access the <a href="https://randomuser.me/documentation#previous">old versions</a> of the API.
|
||||
</p><p>
|
||||
You may expand the collapsed section below to see how you can use <a href="https://realpython.com/python-requests/"><code>requests</code></a> to obtain different versions of the user data using the API:
|
||||
</p><p>
|
||||
You can get a random user from the API using <code>requests</code> as follows:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
<code>get_user()</code> gets one random user in <a href="https://realpython.com/python-json/">JSON</a> format. Note the <code>version</code> parameter. The structure of the returned data has changed quite a bit between earlier versions like <code>"1.1"</code> and the current version <code>"1.3"</code>, but in each case, the actual user data are contained in a list inside the <code>"results"</code> array. The function returns the first—and only—user in this list.
|
||||
</p><p>
|
||||
At the time of writing, the latest version of the API is 1.3 and the data has the following structure:
|
||||
</p><div>
|
||||
<span>JSON</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
One of the members that changed between different versions is <code>"dob"</code>, the date of birth. Note that in version 1.3, this is a JSON object with two members, <code>"date"</code> and <code>"age"</code>.
|
||||
</p><p>
|
||||
Compare the result above with a version 1.1 random user:
|
||||
</p><div>
|
||||
<span>JSON</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Observe that in this older format, the value of the <code>"dob"</code> member is a plain string.
|
||||
</p><p>
|
||||
In this example, you’ll work with the information about the date of birth (<code>dob</code>) for each user. The structure of these data has changed between different versions of the Random User API:
|
||||
</p><div>
|
||||
<span>JSON</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Note that in version 1.1, the date of birth is represented as a simple string, while in version 1.3, it’s a JSON object with two members: <code>"date"</code> and <code>"age"</code>. Say that you want to find the age of a user. Depending on the structure of your data, you’d either need to calculate the age based on the date of birth or look up the age if it’s already available.
|
||||
</p><p>
|
||||
Traditionally, you would detect the structure of the data with an <code>if</code> test, maybe based on the type of the <code>"dob"</code> field. You can approach this differently in Python 3.10. Now, you can use structural pattern matching instead:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The <code>match ... case</code> construct is new in Python 3.10 and is how you perform structural pattern matching. You start with a <code>match</code> statement that specifies what you want to match. In this example, that’s the <code>user</code> data structure.
|
||||
</p><p>
|
||||
One or several <code>case</code> statements follow <code>match</code>. Each <code>case</code> describes one pattern, and the indented block beneath it says what should happen if there’s a match. In this example:
|
||||
</p><ul><li><p>
|
||||
<strong>Line 8</strong> matches a dictionary with a <code>"dob"</code> key whose value is another dictionary with an integer (<code>int</code>) item named <code>"age"</code>. The name <code>age</code> captures its value.
|
||||
</p></li><li><p>
|
||||
<strong>Line 10</strong> matches any dictionary with a <code>"dob"</code> key. The name <code>dob</code> captures its value.
|
||||
</p></li></ul><p>
|
||||
One important feature of pattern matching is that at most one pattern will be matched. Since the pattern on line 10 matches any dictionary with <code>"dob"</code>, it’s important that the more specific pattern on line 8 comes first.
|
||||
</p><p>
|
||||
Before looking closer at the details of the patterns and how they work, try calling <code>get_age()</code> with different data structures to see the result:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Your code can calculate the age correctly for both versions of the user data, which have different dates of birth.
|
||||
</p><p>
|
||||
Look closer at those patterns. The first pattern, <code>{"dob": {"age": int(age)}}</code>, matches version 1.3 of the user data:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The first pattern is a nested pattern. The outer curly braces say that a dictionary with the key <code>"dob"</code> is required. The corresponding value should be a dictionary. This nested dictionary must match the subpattern <code>{"age": int(age)}</code>. In other words, it needs to have an <code>"age"</code> key with an integer value. That value is bound to the name <code>age</code>.
|
||||
</p><p>
|
||||
The second pattern, <code>{"dob": dob}</code>, matches the older version 1.1 of the user data:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
This second pattern is a simpler pattern than the first one. Again, the curly braces indicate that it will match a dictionary. However, any dictionary with a <code>"dob"</code> key is matched because there are no other restrictions specified. The value of that key is bound to the name <code>dob</code>.
|
||||
</p><p>
|
||||
The main takeaway is that you can describe the structure of your data using mostly familiar notation. One striking change, though, is that you can use names like <code>dob</code> and <code>age</code>, which aren’t yet defined. Instead, values from your data are <strong>bound</strong> to these names when a pattern matches.
|
||||
</p><p>
|
||||
You’ve explored some of the power of structural pattern matching in this example. In the next section, you’ll dive a bit more into the details.
|
||||
</p><img src="https://img.realpython.net/c2032f8e413c3322e9ba1029b4adcb98"/><p>
|
||||
These documents give you a lot of background and detail if you’re interested in a deeper dive than what follows.
|
||||
</p><p>
|
||||
Patterns are at the center of structural pattern matching. In this section, you’ll learn about some of the different kinds of patterns that exist:
|
||||
</p><ul><li><strong>Mapping patterns</strong> match mapping structures like dictionaries.</li><li><strong>Sequence patterns</strong> match sequence structures like tuples and lists.</li><li><strong>Capture patterns</strong> bind values to names.</li><li><strong>AS patterns</strong> bind the value of subpatterns to names.</li><li><strong>OR patterns</strong> match one of several different subpatterns.</li><li><strong>Wildcard patterns</strong> match anything.</li><li><strong>Class patterns</strong> match class structures.</li><li><strong>Value patterns</strong> match values stored in attributes.</li><li><strong>Literal patterns</strong> match literal values.</li></ul><p>
|
||||
You already used several of them in the example in the previous section. In particular, you used <strong>mapping patterns</strong> to unravel data stored in dictionaries. In this section, you’ll learn more about how some of these work. All the details are available in the PEPs mentioned above.
|
||||
</p><p>
|
||||
A <strong>capture pattern</strong> is used to capture a match to a pattern and bind it to a name. Consider the following <a href="https://realpython.com/python-recursion/">recursive</a> function that sums a list of numbers:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The first <code>case</code> on line 3 matches the empty list and returns <code>0</code> as its sum. The second <code>case</code> on line 5 uses a <strong>sequence pattern</strong> with two capture patterns to match lists with one or more elements. The first element in the list is captured and bound to the name <code>first</code>. The second capture pattern, <code>*rest</code>, uses <a href="https://realpython.com/python-kwargs-and-args/#unpacking-with-the-asterisk-operators">unpacking syntax</a> to match any number of elements. <code>rest</code> will bind to a list containing all elements of <code>numbers</code> except the first one.
|
||||
</p><p>
|
||||
<code>sum_list()</code> calculates the sum of a list of numbers by recursively adding the first number in the list and the sum of the rest of the numbers. You can use it as follows:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The sum of 4 + 5 + 9 + 4 is correctly calculated to be 22. As an exercise for yourself, you can try to trace the recursive calls to <code>sum_list()</code> to make sure you understand how the code sums the whole list.
|
||||
</p><p>
|
||||
<code>sum_list()</code> handles summing up a list of numbers. Observe what happens if you try to sum anything that isn’t a list:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Passing a string or a number to <code>sum_list()</code> returns <code>None</code>. This occurs because none of the patterns match, and the execution continues after the <code>match</code> block. That happens to be the end of the function, so <code>sum_list()</code> implicitly <a href="https://realpython.com/python-return-statement/#implicit-return-statements">returns <code>None</code></a>.
|
||||
</p><p>
|
||||
Often, though, you want to be alerted about failed matches. You can add a catchall pattern as the final case that handles this by raising an error, for example. You can use the underscore (<code>_</code>) as a <strong>wildcard pattern</strong> that matches anything without binding it to a name. You can add some error handling to <code>sum_list()</code> as follows:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The final <code>case</code> will match anything that doesn’t match the first two patterns. This will raise a descriptive error, for instance, if you try to calculate <code>sum_list(4594)</code>. This is useful when you need to alert your users that some input was not matched as expected.
|
||||
</p><p>
|
||||
Your patterns are still not foolproof, though. Consider what happens if you try to sum a list of strings:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The base case returns <code>0</code>, so therefore the summing only works for types that you can add with numbers. Python doesn’t know how to add numbers and text strings together. You can restrict your pattern to only match integers using a <strong>class pattern</strong>:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Adding <code>int()</code> around <code>first</code> makes sure that the pattern only matches if the value is an integer. This might be too restrictive, though. Your function should be able to sum both <a href="https://realpython.com/python-numbers/#integers">integers</a> and <a href="https://realpython.com/python-numbers/#floating-point-numbers">floating-point numbers</a>, so how can you allow this in your pattern?
|
||||
</p><p>
|
||||
To check whether at least one out of several subpatterns match, you can use an <strong>OR pattern</strong>. OR patterns consist of two or more subpatterns, and the pattern matches if at least one of the subpatterns does. You can use this to match when the first element is either of type <code>int</code> or type <code>float</code>:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
You use the pipe symbol (<code>|</code>) to separate the subpatterns in an OR pattern. Your function now allows summing a list of floating-point numbers:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
There’s a lot of power and flexibility within structural pattern matching, even more than what you’ve seen so far. Some things that aren’t covered in this overview are:
|
||||
</p><ul><li>Using <a href="https://www.python.org/dev/peps/pep-0635/#guards">guards</a> to restrict patterns</li><li>Using <a href="https://www.python.org/dev/peps/pep-0635/#as-patterns">AS patterns</a> to capture the value of subpatterns</li><li>Using <a href="https://www.python.org/dev/peps/pep-0636/#matching-positional-attributes">class patterns</a> to match custom <a href="https://docs.python.org/3/library/enum.html">enums</a> and <a href="https://realpython.com/python-data-classes/">data classes</a></li></ul><p>
|
||||
If you’re interested, have a look in the documentation to learn more about these features as well. In the next section, you’ll learn about literal patterns and value patterns.
|
||||
</p><img src="https://img.realpython.net/8dd76836b26ce79fa0afa59df2458580"/><h3>
|
||||
Matching Literal Patterns
|
||||
</h3><p>
|
||||
A <strong>literal pattern</strong> is a pattern that matches a literal object like an explicit string or number. In a sense, this is the most basic kind of pattern and allows you to emulate <code>switch ... case</code> statements seen in other languages. The following example matches a specific name:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The first <code>case</code> matches the literal string <code>"Guido"</code>. In this case, you use <code>_</code> as a wildcard to print a generic greeting whenever <code>name</code> is not <code>"Guido"</code>. Such literal patterns can sometimes take the place of <code>if ... elif ... else</code> constructs and can play the same role that <code>switch ... case</code> does in some other languages.
|
||||
</p><p>
|
||||
One limitation with structural pattern matching is that you can’t directly match values stored in variables. Say that you’ve defined <code>bdfl = "Guido"</code>. A pattern like <code>case bdfl:</code> will not match <code>"Guido"</code>. Instead, this will be interpreted as a capture pattern that matches anything and binds that value to <code>bdfl</code>, effectively overwriting the old value.
|
||||
</p><p>
|
||||
You can, however, use a <strong>value pattern</strong> to match stored values. A value pattern looks a bit like a capture pattern but uses a previously defined dotted name that holds the value that will be matched against.
|
||||
</p><p>
|
||||
You can, for example, use an <a href="https://docs.python.org/3/library/enum.html">enumeration</a> to create such dotted names:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The first case now uses a value pattern to match <code>Pythonista.BDFL</code>, which is <code>"Guido"</code>. Note that you can use any dotted name in a value pattern. You could, for example, have used a regular class or a module instead of the enumeration.
|
||||
</p><p>
|
||||
To see a bigger example of how to use literal patterns, consider the game of <a href="https://en.wikipedia.org/wiki/Fizz_buzz">FizzBuzz</a>. This is a counting game where you should replace some numbers with words according to the following rules:
|
||||
</p><ul><li>You replace numbers divisible by <strong>3</strong> with <strong>fizz</strong>.</li><li>You replace numbers divisible by <strong>5</strong> with <strong>buzz</strong>.</li><li>You replace numbers divisible by both <strong>3</strong> and <strong>5</strong> with <strong>fizzbuzz</strong>.</li></ul><p>
|
||||
FizzBuzz is sometimes used to introduce conditionals in programming education and as a screening problem in interviews. Even though a solution is quite straightforward, <a href="https://twitter.com/joelgrus">Joel Grus</a> has written a full <a href="https://fizzbuzzbook.com/">book</a> about different ways to program the game.
|
||||
</p><p>
|
||||
A typical solution in Python will use <code>if ... elif ... else</code> as follows:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The <a href="https://realpython.com/python-modulo-operator/"><code>%</code> operator</a> calculates the modulus, which you can use to <a href="https://realpython.com/python-modulo-operator/#python-modulo-operator-in-practice">test divisibility</a>. Namely, if <em>a</em> modulus <em>b</em> is 0 for two numbers <em>a</em> and <em>b</em>, then <em>a</em> is divisible by <em>b</em>.
|
||||
</p><p>
|
||||
In <code>fizzbuzz()</code>, you calculate <code>number % 3</code> and <code>number % 5</code>, which you then use to test for divisibility with 3 and 5. Note that you must do the test for divisibility with both 3 and 5 first. If not, numbers that are divisible by both 3 and 5 will be covered by either the <code>"fizz"</code> or the <code>"buzz"</code> cases instead.
|
||||
</p><p>
|
||||
You can check that your implementation gives the expected result:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
You can confirm for yourself that 3 is divisible by 3, 65 is divisible by 5, and 15 is divisible by both 3 and 5, while 14 and 92 aren’t divisible by either 3 or 5.
|
||||
</p><p>
|
||||
An <code>if ... elif ... else</code> structure where you’re comparing one or a few variables several times over is quite straightforward to rewrite using pattern matching instead. For example, you can do the following:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
You match on both <code>mod_3</code> and <code>mod_5</code>. Each <code>case</code> pattern then matches either the literal number <code>0</code> or the wildcard <code>_</code> on the corresponding values.
|
||||
</p><p>
|
||||
Compare and contrast this version with the previous one. Note how the pattern <code>(0, 0)</code> corresponds to the test <code>mod_3 == 0 and mod_5 == 0</code>, while <code>(0, _)</code> corresponds to <code>mod_3 == 0</code>.
|
||||
</p><p>
|
||||
As you saw earlier, you can use an OR pattern to match on several different patterns. For example, since <code>mod_3</code> can only take the values <code>0</code>, <code>1</code>, and <code>2</code>, you can replace <code>case (_, 0)</code> with <code>case (1, 0) | (2, 0)</code>. Remember that <code>(0, 0)</code> has already been covered.
|
||||
</p><p>
|
||||
The Python core developers have <a href="https://www.python.org/dev/peps/pep-3103/">consciously chosen</a> not to include <code>switch ... case</code> statements in the language earlier. However, there are some third-party packages that do, like <a href="https://pypi.org/project/switchlang/">switchlang</a>, which adds a <code>switch</code> command that also works on earlier versions of Python.
|
||||
</p><img src="https://img.realpython.net/cae48de6b6f52aa978e17ea36747a9fc"/><h2>
|
||||
Type Unions, Aliases, and Guards
|
||||
</h2><p>
|
||||
Reliably, each new Python release brings some improvements to the <a href="https://realpython.com/python-type-checking/">static typing</a> system. Python 3.10 is no exception. In fact, four different PEPs about typing accompany this new release:
|
||||
</p><p>
|
||||
PEP 604 will probably be the most widely used of these changes going forward, but you’ll get a brief overview of each of the features in this section.
|
||||
</p><p>
|
||||
You can use <strong>union types</strong> to declare that a variable can have one of several different types. For example, you’ve been able to type hint a function calculating the mean of a list of numbers, floats, or integers as follows:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The annotation <code>List[Union[float, int]]</code> means that <code>numbers</code> should be a list where each element is either a floating-point number or an integer. This works well, but the notation is a bit verbose. Also, you need to import both <code>List</code> and <code>Union</code> from <code>typing</code>.
|
||||
</p><p>
|
||||
In Python 3.10, you can replace <code>Union[float, int]</code> with the more succinct <code>float | int</code>. Combine this with the ability to use <a href="https://realpython.com/python-list/"><code>list</code></a> instead of <code>typing.List</code> in type hints, which <a href="https://realpython.com/python39-new-features/#type-hint-lists-and-dictionaries-directly">Python 3.9</a> introduced. You can then simplify your code while keeping all the type information:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The annotation of <code>numbers</code> is easier to read now, and as an added bonus, you didn’t need to import anything from <code>typing</code>.
|
||||
</p><p>
|
||||
A special case of union types is when a variable can have either a specific type or be <code>None</code>. You can annotate such <strong>optional types</strong> either as <code>Union[None, T]</code> or, equivalently, <a href="https://realpython.com/python-type-checking/#the-optional-type"><code>Optional[T]</code></a> for some type <code>T</code>. There is no new, special syntax for optional types, but you can use the new union syntax to avoid importing <code>typing.Optional</code>:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
In this example, <code>address</code> is allowed to be either <code>None</code> or a string.
|
||||
</p><p>
|
||||
You can also use the new union syntax at runtime in <code>isinstance()</code> or <code>issubclass()</code> tests:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Traditionally, you’ve used tuples to test for several types at once—for example, <code>(str, int)</code> instead of <code>str | int</code>. This old syntax will still work.
|
||||
</p><p>
|
||||
<strong>Type aliases</strong> allow you to quickly <a href="https://realpython.com/python-type-checking/#type-aliases">define new aliases</a> that can stand in for more complicated type declarations. For example, say that you’re <a href="https://realpython.com/python-type-checking/#example-a-deck-of-cards">representing a playing card</a> using a tuple of suit and rank strings and a deck of cards by a list of such playing card tuples. A deck of cards is then type hinted as <code>list[tuple[str, str]]</code>.
|
||||
</p><p>
|
||||
To simplify type annotation, you define type aliases as follows:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
This usually works okay. However, it’s often not possible for the type checker to know whether such a statement is a type alias or just the definition of a regular global variable. To help the type checker—or really, help the type checker help you—you can now explicitly annotate type aliases:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Adding the <code>TypeAlias</code> annotation clarifies the intention, both to a type checker and to anyone reading your code.
|
||||
</p><p>
|
||||
<strong>Type guards</strong> are used to narrow down union types. The following function takes in either a string or <code>None</code> but always returns a tuple of strings representing a playing card:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The highlighted line works as a type guard, and static type checkers are able to realize that <code>suit</code> is necessarily a string when it’s returned.
|
||||
</p><p>
|
||||
Currently, the type checkers can only use a <a href="https://www.python.org/dev/peps/pep-0647/#motivation">few different constructs</a> to narrow down union types in this way. With the new <a href="https://docs.python.org/3.10/library/typing.html#typing.TypeGuard"><code>typing.TypeGuard</code></a>, you can annotate custom functions that can be used to narrow down union types:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
<code>is_deck_of_cards()</code> should return <code>True</code> or <code>False</code> depending on whether <code>obj</code> represents a <code>Deck</code> object or not. You can then use your guard function, and the type checker will be able to narrow down the types correctly:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Inside of the <code>if</code> block, the type checker knows that <code>card_or_deck</code> is, in fact, of the type <code>Deck</code>. See <a href="https://www.python.org/dev/peps/pep-0647/">PEP 647</a> for more details.
|
||||
</p><p>
|
||||
The final new typing feature is <strong>Parameter Specification Variables</strong>, which is related to <a href="https://realpython.com/python-type-checking/#type-variables">type variables</a>. Consider the definition of a <a href="https://realpython.com/primer-on-python-decorators/">decorator</a>. In general, it looks something like the following:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The annotations mean that the function returned by the decorator is a callable with some parameters and the same return type, <code>R</code>, as the function passed into the decorator. The <a href="https://realpython.com/python-ellipsis/">ellipsis</a> (<code>...</code>) in the function header correctly allows any number of parameters, and each of those parameters can be of any type. However, there’s no validation that the returned callable has the same parameters as the function that was passed in. In practice, this means that type checkers aren’t able to check decorated functions properly.
|
||||
</p><p>
|
||||
Unfortunately, you can’t use <code>TypeVar</code> for the parameters because you don’t know how many parameters the function will have. In Python 3.10, you’ll have access to <a href="https://docs.python.org/3.10/library/typing.html#typing.ParamSpec"><code>ParamSpec</code></a> in order to type hint these kinds of callables properly. <code>ParamSpec</code> works similarly to <code>TypeVar</code> but stands in for several parameters at once. You can rewrite your decorator as follows to take advantage of <code>ParamSpec</code>:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Note that you also use <code>P</code> when you annotate <code>wrapper()</code>. You can also use the new <a href="https://docs.python.org/3.10/library/typing.html#typing.Concatenate"><code>typing.Concatenate</code></a> to add types to <code>ParamSpec</code>. See the <a href="https://docs.python.org/3.10/library/typing.html">documentation</a> and <a href="https://www.python.org/dev/peps/pep-0612/">PEP 612</a> for details and examples.
|
||||
</p><img src="https://img.realpython.net/eb1fdbdd9dab50bc687468a6fffd3d0b"/><h2>
|
||||
Stricter Zipping of Sequences
|
||||
</h2><p>
|
||||
<a href="https://realpython.com/python-zip-function/"><code>zip()</code></a> is a <a href="https://docs.python.org/3/library/functions.html#built-in-functions">built-in function</a> in Python that can combine elements from several sequences. Python 3.10 introduces the new <code>strict</code> parameter, which adds a runtime test to check that all sequences being zipped have the same length.
|
||||
</p><p>
|
||||
As an example, consider the following table of <a href="https://www.lego.com/">Lego</a> sets:
|
||||
</p><table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>
|
||||
Name
|
||||
</th>
|
||||
<th>
|
||||
Set Number
|
||||
</th>
|
||||
<th>
|
||||
Pieces
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
<a href="https://brickset.com/sets/21024-1/Louvre">Louvre</a>
|
||||
</td>
|
||||
<td>
|
||||
21024
|
||||
</td>
|
||||
<td>
|
||||
695
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<a href="https://brickset.com/sets/75978-1/Diagon-Alley">Diagon Alley</a>
|
||||
</td>
|
||||
<td>
|
||||
75978
|
||||
</td>
|
||||
<td>
|
||||
5544
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<a href="https://brickset.com/sets/92176-1/NASA-Apollo-Saturn-V">NASA Apollo Saturn V</a>
|
||||
</td>
|
||||
<td>
|
||||
92176
|
||||
</td>
|
||||
<td>
|
||||
1969
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<a href="https://brickset.com/sets/75192-1/Millennium-Falcon">Millennium Falcon</a>
|
||||
</td>
|
||||
<td>
|
||||
75192
|
||||
</td>
|
||||
<td>
|
||||
7541
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<a href="https://brickset.com/sets/21028-1/New-York-City">New York City</a>
|
||||
</td>
|
||||
<td>
|
||||
21028
|
||||
</td>
|
||||
<td>
|
||||
598
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table><p>
|
||||
One way to represent these data in plain Python would be with each column as a list. It could look something like this:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Note that you have three independent lists, but there’s an implicit correspondence between their elements. The first name (<code>"Louvre"</code>), the first set number (<code>"21024"</code>), and the first number of pieces (<code>695</code>) all describe the first Lego set.
|
||||
</p><p>
|
||||
<code>zip()</code> can be used to iterate over these three lists in parallel:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Note how each line collects information from all three lists and shows information about one particular set. This is a very common pattern that’s used in a lot of different Python code, including <a href="https://www.python.org/dev/peps/pep-0618/#examples">in the standard library</a>.
|
||||
</p><p>
|
||||
You can also add <code>list()</code> to collect the contents of all three lists in a single, nested list of tuples:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Note how the nested list closely resembles the original table.
|
||||
</p><p>
|
||||
The dark side of using <code>zip()</code> is that it’s quite easy to introduce a subtle bug that can be hard to discover. Note what happens if there’s a missing item in one of your lists:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
All the information about the New York City set disappeared! Additionally, the set numbers for Saturn V and Millennium Falcon are wrong. If your datasets are bigger, these kinds of errors can be very hard to discover. And even when you observe that something’s wrong, it’s not always easy to diagnose and fix.
|
||||
</p><p>
|
||||
The issue is that you assumed that the three lists have the same number of elements and that the information is in the same order in each list. After <code>set_numbers</code> gets corrupted, this assumption is no longer true.
|
||||
</p><p>
|
||||
<a href="https://www.python.org/dev/peps/pep-0618/">PEP 618</a> introduces a new <code>strict</code> keyword parameter to <code>zip()</code> that you can use to confirm all sequences have the same length. In your example, it would raise an error alerting you to the corrupted list:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
When the iteration reaches the New York City Lego set, the second argument <code>set_numbers</code> is already exhausted, while there are still elements left in the first argument <code>names</code>. Instead of silently giving the wrong result, your code fails with an error, and you can take action to find and fix the mistake.
|
||||
</p><p>
|
||||
There are use cases when you want to combine sequences of unequal length. Expand the box below to see how <code>zip()</code> and <code>itertools.zip_longest()</code> handle these:
|
||||
</p><p>
|
||||
The <a href="https://realpython.com/python-itertools/#what-is-itertools-and-why-should-you-use-it">following idiom</a> divides the Lego sets into pairs:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
There are five sets, a number that doesn’t divide evenly into pairs. In this case, the default behavior of <code>zip()</code>, where the last element is dropped, might make sense. You could use <code>strict=True</code> here as well, but that would raise an error when your list can’t be split into pairs. A third option, which could be the best in this case, is to use <a href="https://docs.python.org/3/library/itertools.html#itertools.zip_longest"><code>zip_longest()</code></a> from the <a href="https://realpython.com/python-itertools/"><code>itertools</code></a> standard library.
|
||||
</p><p>
|
||||
As the name suggests, <code>zip_longest()</code> combines sequences until the longest sequence is exhausted. If you use <code>zip_longest()</code> to divide the Lego sets, it becomes more explicit that New York City doesn’t have any pairing:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Note that <code>'NYC'</code> shows up in the last tuple together with an empty string. You can control what’s filled in for missing values with the <code>fillvalue</code> parameter.
|
||||
</p><p>
|
||||
While <code>strict</code> is not really adding any new functionality to <code>zip()</code>, it can help you avoid those hard-to-find bugs.
|
||||
</p><img src="https://img.realpython.net/16bf1efe41b538fae54711c58c701f0e"/><h2>
|
||||
New Functions in the <code>statistics</code> Module
|
||||
</h2><p>
|
||||
The <a href="https://docs.python.org/3/library/statistics.html"><code>statistics</code></a> module was added to the standard library all the way back in 2014 with the release of <a href="https://www.python.org/downloads/release/python-340/">Python 3.4</a>. The intent of <code>statistics</code> is to make <a href="https://realpython.com/python-statistics/">statistical calculations</a> at the <a href="https://www.python.org/dev/peps/pep-0450/">level of graphing calculators</a> available in Python.
|
||||
</p><p>
|
||||
Python 3.10 adds a few multivariable functions to <code>statistics</code>:
|
||||
</p><ul><li><strong><code>correlation()</code></strong> to calculate Pearson’s <a href="https://realpython.com/numpy-scipy-pandas-correlation-python/">correlation</a> coefficient for two variables</li><li><strong><code>covariance()</code></strong> to calculate sample <a href="https://en.wikipedia.org/wiki/Covariance">covariance</a> for two variables</li><li><strong><code>linear_regression()</code></strong> to calculate the slope and intercept in a <a href="https://realpython.com/linear-regression-in-python/">linear regression</a></li></ul><p>
|
||||
You can use each function to describe a certain aspect of the relationship between two variables. As an example, say that you have data from a set of blog posts—the number of words in each blog post and the number of views each post has had over some time period:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
You now want to investigate whether there’s any (linear) relationship between the number of words and number of views. In Python 3.10, you can calculate the <strong>correlation</strong> between <code>words</code> and <code>views</code> with the new <a href="https://docs.python.org/3.10/library/statistics.html#statistics.correlation"><code>correlation()</code></a> function:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The correlation between two variables is always a number between -1 and 1. If it’s close to 0, then there’s little correspondence between them, while a correlation close to -1 or 1 indicates that the behaviors of the two variables tend to follow each other. In this example, a correlation of 0.45 indicates that there’s a tendency for posts with more words to have more views, although it’s not a strong connection.
|
||||
</p><p>
|
||||
You can also calculate the <strong>covariance</strong> between <code>words</code> and <code>views</code>. The covariance is another measure of the joint variability between two variables. You can calculate it with <a href="https://docs.python.org/3.10/library/statistics.html#statistics.covariance"><code>covariance()</code></a>:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
In contrast to correlation, covariance is an absolute measure. It should be interpreted in the context of the variability within the variables themselves. In fact, you can normalize the covariance by the <a href="https://en.wikipedia.org/wiki/Standard_deviation">standard deviation</a> of each variable to recover <a href="https://en.wikipedia.org/wiki/Pearson_correlation_coefficient">Pearson’s correlation coefficient</a>:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Note that this matches your earlier correlation coefficient exactly.
|
||||
</p><p>
|
||||
A third way of looking at the linear correspondence between the two variables is through <strong>simple linear regression</strong>. You do the <a href="https://en.wikipedia.org/wiki/Simple_linear_regression">linear regression</a> by calculating two numbers, <em>slope</em> and <em>intercept</em>, so that the (squared) error is minimized in the approximation <em>number of views</em> = <em>slope</em> × <em>number of words</em> + <em>intercept</em>.
|
||||
</p><p>
|
||||
In Python 3.10, you can use <a href="https://docs.python.org/3.10/library/statistics.html#statistics.linear_regression"><code>linear_regression()</code></a>:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Based on this regression, a post with 10,074 words could expect about 0.2424 × 10074 + 1104 = 3546 views. However, as you saw earlier, the correlation between the number of words and the number of views is quite weak. Therefore, you shouldn’t expect this prediction to be very accurate.
|
||||
</p><p>
|
||||
The <code>LinearRegression</code> object is a <a href="https://realpython.com/python-namedtuple/">named tuple</a>. This means that you can unpack the slope and intercept directly:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Here, you use <code>slope</code> and <code>intercept</code> to predict the number of views on a blog post with 10,074 words.
|
||||
</p><p>
|
||||
You still want to use some of the more advanced packages like pandas and statsmodels if you do a lot of statistical analysis. With the new additions to <code>statistics</code> in Python 3.10, however, you have the chance to do basic analysis more easily without bringing in third-party dependencies.
|
||||
</p><img src="https://img.realpython.net/39d33f31dff9ce5e91d62b0a7b0c7420"/><h2>
|
||||
Other Pretty Cool Features
|
||||
</h2><p>
|
||||
So far, you’ve seen the biggest and most impactful new features in Python 3.10. In this section, you’ll get a glimpse of a few of the other changes that the new version brings along. If you’re curious about all the changes made for this new version, check out the <a href="https://docs.python.org/3.10/whatsnew/3.10.html">documentation</a>.
|
||||
</p><h3>
|
||||
Default Text Encodings
|
||||
</h3><p>
|
||||
When you open a text file, the default encoding used to interpret the characters is system dependent. In particular, <a href="https://docs.python.org/3.10/library/locale.html#locale.getpreferredencoding"><code>locale.getpreferredencoding()</code></a> is used. On Mac and Linux, this usually returns <code>"UTF-8"</code>, while the result on Windows is more varied.
|
||||
</p><p>
|
||||
You should therefore always specify an encoding when you attempt to open a text file:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
If you don’t explicitly specify an encoding, the preferred locale encoding is used, and you could experience that a file that can be read on one computer fails to open on another.
|
||||
</p><p>
|
||||
Python 3.7 introduced <a href="https://docs.python.org/3.10/library/os.html#utf8-mode">UTF-8 mode</a>, which allows you to force your programs to use UTF-8 encoding independent of the locale encoding. You can enable UTF-8 mode by giving the <code>-X utf8</code> command-line option to the <code>python</code> executable or by setting the <code>PYTHONUTF8</code> environment variable.
|
||||
</p><p>
|
||||
In Python 3.10, you can activate a warning that will tell you when a text file is opened without a specified encoding. Consider the following script, which doesn’t specify an encoding:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The program will echo one or more text files back to the console, but with each line reversed. Run the program on itself with the <a href="https://docs.python.org/3.10/library/io.html#io-encoding-warning">encoding warning</a> enabled:
|
||||
</p><div>
|
||||
<span>Shell</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Note the <code>EncodingWarning</code> printed to the console. The command-line option <code>-X warn_default_encoding</code> activates it. The warning will disappear if you specify an encoding—for example, <code>encoding="utf-8"</code>—when you open the file.
|
||||
</p><p>
|
||||
There are times when you want to use the user-defined local encoding. You can still do so by explicitly using <code>encoding="locale"</code>. However, it’s recommended to use UTF-8 whenever possible. You can check out <a href="https://www.python.org/dev/peps/pep-0597/">PEP 597</a> for more information.
|
||||
</p><h3>
|
||||
Asynchronous Iteration
|
||||
</h3><p>
|
||||
<a href="https://realpython.com/python-async-features/">Asynchronous programming</a> is a powerful programming paradigm that’s been available in Python <a href="https://www.python.org/dev/peps/pep-0492/">since version 3.5</a>. You can recognize an asynchronous program by its use of the <code>async</code> keyword or <a href="https://realpython.com/python-classes/#special-methods-and-protocols">special methods</a> that <a href="https://www.python.org/dev/peps/pep-0492/#why-magic-methods-start-with-a">start with <code>.__a</code></a> like <a href="https://docs.python.org/3/reference/datamodel.html#object.__aiter__"><code>.__aiter__()</code></a> or <a href="https://docs.python.org/3/reference/datamodel.html#object.__aenter__"><code>.__aenter__()</code></a>.
|
||||
</p><p>
|
||||
In Python 3.10, two new asynchronous <a href="https://docs.python.org/3/library/functions.html#built-in-functions">built-in functions</a> are added: <a href="https://docs.python.org/3.10/library/functions.html#aiter"><code>aiter()</code></a> and <a href="https://docs.python.org/3.10/library/functions.html#anext"><code>anext()</code></a>. In practice, these functions call the <code>.__aiter__()</code> and <code>.__anext__()</code> special methods—analogous to the regular <code>iter()</code> and <code>next()</code>—so no new functionality is added. These are convenience functions that make your code more readable.
|
||||
</p><p>
|
||||
In other words, in the newest version of Python, the following statements—where <code>things</code> is an <a href="https://www.python.org/dev/peps/pep-0492/#asynchronous-iterators-and-async-for">asynchronous iterable</a>—are equivalent:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
In either case, <code>it</code> ends up as an asynchronous iterator. Expand the following box to see a complete example using <code>aiter()</code> and <code>anext()</code>:
|
||||
</p><p>
|
||||
The following program counts the number of lines in several files. In practice, you use Python’s ability to iterate over files to count the number of lines. The script uses asynchronous iteration in order to handle several files concurrently.
|
||||
</p><p>
|
||||
Note that you need to install the third-party <a href="https://pypi.org/project/aiofiles/"><code>aiofiles</code></a> package with <a href="https://realpython.com/what-is-pip/"><code>pip</code></a> before running this code:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
<code>asyncio</code> is used to create and run one asynchronous task per filename. <code>count_lines()</code> opens one file asynchronously and iterates through it using <code>aiter()</code> and <code>anext()</code> in order to count the number of lines.
|
||||
</p><p>
|
||||
See <a href="https://www.python.org/dev/peps/pep-0525/">PEP 525</a> to learn more about asynchronous iteration.
|
||||
</p><img src="https://img.realpython.net/913fd28f526ec8aca047551bce4892b6"/><h3>
|
||||
Context Manager Syntax
|
||||
</h3><p>
|
||||
<a href="https://realpython.com/python-with-statement/">Context managers</a> are great for managing resources in your programs. Until recently, though, their syntax has included an uncommon wart. You <a href="https://www.python.org/dev/peps/pep-0617/#some-rules-are-not-actually-ll-1">haven’t been allowed</a> to use parentheses to break long <code>with</code> statements like this:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
In earlier versions of Python, this causes an <code>invalid syntax</code> error message. Instead, you need to use a backslash (<code>\</code>) if you want to control where you break your lines:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
While <a href="https://realpython.com/python-program-structure/#explicit-line-continuation">explicit line continuation</a> with backslashes is possible in Python, PEP 8 <a href="https://www.python.org/dev/peps/pep-0008/#maximum-line-length">discourages it</a>. The <a href="https://black.readthedocs.io/">Black</a> formatting tool <a href="https://black.readthedocs.io/en/stable/the_black_code_style/current_style.html">avoids</a> backslashes completely.
|
||||
</p><p>
|
||||
In Python 3.10, you’re now allowed to add parentheses around <code>with</code> statements to your heart’s content. Especially if you’re employing several context managers at once, like in the example above, this can help improve the readability of your code. Python’s <a href="https://docs.python.org/3.10/whatsnew/3.10.html#parenthesized-context-managers">documentation</a> shows a few other possibilities with this new syntax.
|
||||
</p><p>
|
||||
One small <strong>fun fact</strong>: parenthesized <code>with</code> statements actually work in version 3.9 of <a href="https://realpython.com/cpython-source-code-guide/">CPython</a>. Their implementation came almost for free with the introduction of the <a href="https://realpython.com/python39-new-features/#a-more-powerful-python-parser">PEG parser</a> in <a href="https://realpython.com/python39-new-features/">Python 3.9</a>. The reason that this is called a Python 3.10 feature is that using the PEG parser is voluntary in Python 3.9, while Python 3.9, with the old LL(1) parser, doesn’t support parenthesized <code>with</code> statements.
|
||||
</p><h3>
|
||||
Modern and Secure SSL
|
||||
</h3><p>
|
||||
Security can be challenging! A good rule of thumb is to avoid rolling your own security algorithms and instead rely on established packages.
|
||||
</p><p>
|
||||
Python uses <a href="https://www.openssl.org/">OpenSSL</a> for different cryptographic features that are exposed in the <a href="https://docs.python.org/3/library/hashlib.html"><code>hashlib</code></a>, <a href="https://docs.python.org/3/library/hmac.html"><code>hmac</code></a>, and <a href="https://docs.python.org/3/library/ssl.html"><code>ssl</code></a> standard library modules. Your system can manage OpenSSL, or a Python installer can include OpenSSL.
|
||||
</p><p>
|
||||
Python 3.9 supports using any of the <a href="https://en.wikipedia.org/wiki/OpenSSL#Major_version_releases">OpenSSL versions</a> 1.0.2 LTS, 1.1.0, and 1.1.1 LTS. Both OpenSSL 1.0.2 LTS and OpenSSL 1.1.0 are past their lifetime, so Python 3.10 will only support OpenSSL 1.1.1 LTS, as described in the following table:
|
||||
</p><table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>
|
||||
Open SSL version
|
||||
</th>
|
||||
<th>
|
||||
Python 3.9
|
||||
</th>
|
||||
<th>
|
||||
Python 3.10
|
||||
</th>
|
||||
<th>
|
||||
End-of-life
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
1.0.2 LTS
|
||||
</td>
|
||||
<td>
|
||||
✔
|
||||
</td>
|
||||
<td>
|
||||
✖
|
||||
</td>
|
||||
<td>
|
||||
December 20, 2019
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
1.1.0
|
||||
</td>
|
||||
<td>
|
||||
✔
|
||||
</td>
|
||||
<td>
|
||||
✖
|
||||
</td>
|
||||
<td>
|
||||
September 10, 2019
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
1.1.1 LTS
|
||||
</td>
|
||||
<td>
|
||||
✔
|
||||
</td>
|
||||
<td>
|
||||
✔
|
||||
</td>
|
||||
<td>
|
||||
September 11, 2023
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table><p>
|
||||
This end of support for older versions will only affect you if you need to upgrade the system Python on an older operating system. If you use macOS or Windows, or if you install Python from <a href="https://www.python.org/">python.org</a> or use <a href="https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html">(Ana)Conda</a>, you’ll see no change.
|
||||
</p><p>
|
||||
However, <a href="https://ubuntu.com/">Ubuntu</a> 18.04 LTS uses OpenSSL 1.1.0, while <a href="https://www.redhat.com/en/technologies/linux-platforms/enterprise-linux">Red Hat Enterprise Linux</a> (RHEL) 7 and <a href="https://www.centos.org/">CentOS</a> 7 both use OpenSSL 1.0.2 LTS. If you need to run Python 3.10 on these systems, you should look at installing it yourself using either the <a href="https://www.python.org">python.org</a> or Conda installer.
|
||||
</p><p>
|
||||
Dropping support for older versions of OpenSSL will make Python more secure. It’ll also help the Python developers in that code will be easier to maintain. Ultimately, this helps you because your Python experience will be more robust. See <a href="https://www.python.org/dev/peps/pep-0644/">PEP 644</a> for more details.
|
||||
</p><h3>
|
||||
More Information About Your Python Interpreter
|
||||
</h3><p>
|
||||
The <a href="https://docs.python.org/3/library/sys.html"><code>sys</code></a> module contains a lot of information about your system, the current Python runtime, and the script currently being executed. You can, for example, inquire about the paths where <a href="https://realpython.com/python-import/#pythons-import-path">Python looks for modules</a> with <a href="https://docs.python.org/3/library/sys.html#sys.path"><code>sys.path</code></a> and see all modules that <a href="https://realpython.com/python-import/#import-internals">have been imported</a> in the current session with <a href="https://docs.python.org/3/library/sys.html#sys.modules"><code>sys.modules</code></a>.
|
||||
</p><p>
|
||||
In Python 3.10, <code>sys</code> has two new attributes. First, you can now get a list of the names of all modules in the standard library:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Here, you can see that there are around 300 modules in the standard library, several of which start with the letter <code>z</code>. Note that only top-level modules and packages are listed. Subpackages like <a href="https://realpython.com/python38-new-features/#importlibmetadata"><code>importlib.metadata</code></a> don’t get a separate entry.
|
||||
</p><p>
|
||||
You will probably not be using <a href="https://docs.python.org/3.10/library/sys.html#sys.stdlib_module_names"><code>sys.stdlib_module_names</code></a> all that often. Still, the list ties in nicely with similar introspection features like <a href="https://docs.python.org/3/library/keyword.html#keyword.kwlist"><code>keyword.kwlist</code></a> and <a href="https://docs.python.org/3/library/sys.html#sys.builtin_module_names"><code>sys.builtin_module_names</code></a>.
|
||||
</p><p>
|
||||
One possible use case for the new attribute is to identify which of the currently imported modules are third-party dependencies:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
You find the imported top-level modules by looking at names in <code>sys.modules</code> that don’t have a dot in their name. By comparing them to the standard library module names, you find that <a href="https://realpython.com/numpy-array-programming/"><code>numpy</code></a>, <a href="https://realpython.com/python-packages/#dateutil-for-working-with-dates-and-times"><code>dateutil</code></a>, and <a href="https://realpython.com/python-pandas-tricks/"><code>pandas</code></a> are some of the imported third-party modules in this example.
|
||||
</p><p>
|
||||
The other new attribute is <a href="https://docs.python.org/3.10/library/sys.html#sys.orig_argv"><code>sys.orig_argv</code></a>. This is related to <a href="https://docs.python.org/3/library/sys.html#sys.argv"><code>sys.argv</code></a>, which holds the <a href="https://realpython.com/python-command-line-arguments/#the-sysargv-array">command-line arguments</a> given to your program when it was started. In contrast, <code>sys.orig_argv</code> lists the command-line arguments passed to the <code>python</code> executable itself. Consider the following example:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
This script echoes back the <code>orig_argv</code> and <code>argv</code> lists. Run it to see how the information is captured:
|
||||
</p><div>
|
||||
<span>Shell</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Essentially, all arguments—including the name of the Python executable—end up in <code>orig_argv</code>. This is in contrast to <code>argv</code>, which only contains the arguments that aren’t handled by <code>python</code> itself.
|
||||
</p><p>
|
||||
Again, this is not a feature that you’ll use a lot. If your program needs to concern itself with how it’s being run, you’re usually better off relying on information that’s already exposed instead of trying to parse this list. For example, you can choose to use the <a href="#stricter-zipping-of-sequences">strict <code>zip()</code> mode</a> only when your script is not running with the optimized flag, <code>-O</code>, like this:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The <a href="https://docs.python.org/3/library/constants.html#__debug__"><code>__debug__</code></a> flag is set when the interpreter starts. It’ll be <code>False</code> if you’re running <code>python</code> with <a href="https://docs.python.org/3/using/cmdline.html#cmdoption-o"><code>-O</code></a> or <a href="https://docs.python.org/3/using/cmdline.html#cmdoption-oo"><code>-OO</code></a> specified, and <code>True</code> otherwise. Using <code>__debug__</code> is usually preferable to <code>"-O" not in sys.orig_argv</code> or some similar construct.
|
||||
</p><p>
|
||||
One of the <a href="https://bugs.python.org/issue23427#msg371028">motivating use cases</a> for <code>sys.orig_argv</code> is that you can use it to spawn a new Python process with the same or modified command-line arguments as your current process.
|
||||
</p><img src="https://img.realpython.net/e8b8e877da2a454b3a6930fecd28c95c"/><h3>
|
||||
Future Annotations
|
||||
</h3><p>
|
||||
<a href="https://realpython.com/python-type-checking/#annotations">Annotations</a> were introduced in Python 3 to give you a way to attach metadata to variables, function parameters, and return values. They are most commonly used to add type hints to your code.
|
||||
</p><p>
|
||||
One challenge with annotations is that they must be valid Python code. For one thing, this makes it <a href="https://realpython.com/python37-new-features/#typing-enhancements">hard to type hint</a> recursive classes. <a href="https://www.python.org/dev/peps/pep-0563/">PEP 563</a> introduced <a href="https://realpython.com/python-news-april-2021/#pep-563-pep-649-and-the-future-of-python-type-annotations">postponed evaluation of annotations</a>, making it possible to annotate with names that haven’t yet been defined. Since Python 3.7, you can activate postponed evaluation of annotations with a <a href="https://docs.python.org/3/library/__future__.html"><code>__future__</code></a> import:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
The intention was that postponed evaluation would become the default at some point in the future. After the <a href="https://pyfound.blogspot.com/2020/04/the-2020-python-language-summit.html">2020 Python Language Summit</a>, it was decided to make this happen in Python 3.10.
|
||||
</p><p>
|
||||
However, after more testing, it became clear that postponed evaluation didn’t work well for projects that use annotations at runtime. Key people in the <a href="https://realpython.com/fastapi-python-web-apis/">FastAPI</a> and the <a href="https://pydantic-docs.helpmanual.io/">Pydantic</a> projects <a href="https://dev.to/tiangolo/the-future-of-fastapi-and-pydantic-is-bright-3pbm">voiced their concerns</a>. At the last minute, it was decided to reschedule these changes for Python 3.11.
|
||||
</p><p>
|
||||
To ease the transition into future behavior, a few changes have been made in Python 3.10 as well. Most importantly, a new <a href="https://docs.python.org/3.10/library/inspect.html#inspect.get_annotations"><code>inspect.get_annotations()</code></a> function has been added. You should call this to access annotations at runtime:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
Check out <a href="https://docs.python.org/3.10/howto/annotations.html">Annotations Best Practices</a> for details.
|
||||
</p><h2>
|
||||
How to Detect Python 3.10 at Runtime
|
||||
</h2><p>
|
||||
Python 3.10 is the first version of Python with a two-digit minor version number. While this is mostly an interesting fun fact and an indication that Python 3 has been around for quite some time, it does also have some practical consequences.
|
||||
</p><p>
|
||||
When your code needs to do something specific based on the version of Python at runtime, you’ve gotten away with doing a <a href="https://docs.python.org/3/reference/expressions.html#value-comparisons">lexicographical</a> comparison of version strings until now. While it’s never been good practice, it’s been possible to do the following:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
In Python 3.10, this code will raise <code>SystemExit</code> and stop your program. This happens because, as strings, <code>"3.10"</code> is less than <code>"3.6"</code>.
|
||||
</p><p>
|
||||
The correct way to compare version numbers is to use tuples of numbers:
|
||||
</p><div>
|
||||
<span>Python</span>
|
||||
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
<a href="https://docs.python.org/3/library/sys.html#sys.version_info"><code>sys.version_info</code></a> is a tuple object you can use for comparisons.
|
||||
</p><p>
|
||||
If you’re doing these kinds of comparisons in your code, you should check your code with <a href="https://pypi.org/project/flake8-2020/">flake8-2020</a> to make sure you’re handling versions correctly:
|
||||
</p><div>
|
||||
<span>Shell</span>
|
||||
</div><template>
|
||||
<span>Copied!</span>
|
||||
</template><p>
|
||||
With the <code>flake8-2020</code> extension activated, you’ll get a recommendation about replacing <code>sys.version</code> with <code>sys.version_info</code>.
|
||||
</p><img src="https://img.realpython.net/fc3dcce3b30783158d89077cf5a8810e"/><h2>
|
||||
So, Should You Upgrade to Python 3.10?
|
||||
</h2><p>
|
||||
You’ve now seen the coolest features of the newest and latest version of Python. The question now is whether you should upgrade to Python 3.10, and if yes, when you should do so. There are two different aspects to consider when thinking about upgrading to Python 3.10:
|
||||
</p><ol><li>Should you upgrade your environment so that you <strong>run your code</strong> with the Python 3.10 interpreter?</li><li>Should you <strong>write your code</strong> using the new Python 3.10 features?</li></ol><p>
|
||||
Clearly, if you want to test out structural pattern matching or any of the other cool new features you’ve read about here, you need Python 3.10. It’s possible to install the latest version side by side with your current Python version. A straightforward way to do this is to use an environment manager like <a href="https://realpython.com/intro-to-pyenv/">pyenv</a> or <a href="https://realpython.com/python-windows-machine-learning-setup/">Conda</a>. You can also <a href="https://realpython.com/python-versions-docker/">use Docker</a> to run Python 3.10 without installing it locally.
|
||||
</p><p>
|
||||
Python 3.10 has been through about five months of beta testing, so there shouldn’t be any big issues with starting to use it for your own development. You may find that some of your dependencies don’t immediately have <a href="https://realpython.com/python-wheels/">wheels for Python 3.10</a> available, which makes them more cumbersome to install. But in general, using the newest Python for local development is fairly safe.
|
||||
</p><p>
|
||||
As always, you should be careful before upgrading your production environment. Be vigilant about testing that your code runs well on the new version. In particular, you want to be on the lookout for features that are <a href="https://docs.python.org/3.10/whatsnew/3.10.html#deprecated">deprecated</a> or <a href="https://docs.python.org/3.10/whatsnew/3.10.html#removed">removed</a>.
|
||||
</p><p>
|
||||
Whether you can start using the new features in your code or not depends on your user base and the environment where your code is running. If you can guarantee that Python 3.10 is available, then there’s no danger in using the new union type syntax or any other new feature.
|
||||
</p><p>
|
||||
If you’re distributing an app or a library that’s used by others instead, you may want to be a bit more conservative. Currently, <a href="https://www.python.org/dev/peps/pep-0494">Python 3.6</a> is the oldest officially supported Python version. It reaches end-of-life in December 2021, after which <a href="https://www.python.org/dev/peps/pep-0537">Python 3.7</a> will be the minimum supported version.
|
||||
</p><p>
|
||||
The documentation includes a useful guide about <a href="https://docs.python.org/3.10/whatsnew/3.10.html#porting-to-python-3-10">porting your code to Python 3.10</a>. Check it out for more details!
|
||||
</p><h2>
|
||||
Conclusion
|
||||
</h2><p>
|
||||
The release of a new Python version is always worth celebrating. Even if you can’t start using the new features right away, they’ll become broadly available and part of your daily life within a few years.
|
||||
</p><p>
|
||||
<strong>In this tutorial, you’ve seen new features like:</strong>
|
||||
</p><ul><li>Friendlier <strong>error messages</strong></li><li>Powerful <strong>structural pattern matching</strong></li><li><strong>Type hint</strong> improvements</li><li>Safer <strong>combination of sequences</strong></li><li>New <strong>statistics functions</strong></li></ul><p>
|
||||
For more Python 3.10 tips and a discussion with members of the <em>Real Python</em> team, check out <a href="https://realpython.com/podcasts/rpp/81/">Real Python Podcast Episode #81</a>.
|
||||
</p><p>
|
||||
Have fun trying out the new features! Share your experiences in the comments below.
|
||||
</p><p>
|
||||
<span> Watch Now</span> This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: <a href="/courses/cool-new-features-python-310/"><strong>Cool New Features in Python 3.10</strong></a>
|
||||
</p><p>
|
||||
Get a short & sweet <strong>Python Trick</strong> delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.
|
||||
</p><img loading="lazy" src="/static/pytrick-dict-merge.4201a0125a5e.png" alt="Python Tricks Dictionary Merge"/><img loading="lazy" src="https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/gahjelle.470149ee709e.jpg&w=800&h=800&mode=crop&sig=e9b761c6cf1359953014dba05554f5424eb116e1" srcset="https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/gahjelle.470149ee709e.jpg&w=200&h=200&mode=crop&sig=c6390201e73d3e09429d73da5bb29c17ab10403a 200w, https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/gahjelle.470149ee709e.jpg&w=266&h=266&mode=crop&sig=7df7c39b123c3f9d8a4597311d09c3bd947f5fac 266w, https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/gahjelle.470149ee709e.jpg&w=400&h=400&mode=crop&sig=fcea459ee24a7b320573cadee324cf75509dc1d6 400w, https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/gahjelle.470149ee709e.jpg&w=800&h=800&mode=crop&sig=e9b761c6cf1359953014dba05554f5424eb116e1 800w" sizes="(min-width: 580px) 154px, calc(33.08vw - 24px)" alt="Geir Arne Hjelle"/><img loading="lazy" src="https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/gahjelle.470149ee709e.jpg&w=800&h=800&mode=crop&sig=e9b761c6cf1359953014dba05554f5424eb116e1" srcset="https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/gahjelle.470149ee709e.jpg&w=200&h=200&mode=crop&sig=c6390201e73d3e09429d73da5bb29c17ab10403a 200w, https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/gahjelle.470149ee709e.jpg&w=266&h=266&mode=crop&sig=7df7c39b123c3f9d8a4597311d09c3bd947f5fac 266w, https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/gahjelle.470149ee709e.jpg&w=400&h=400&mode=crop&sig=fcea459ee24a7b320573cadee324cf75509dc1d6 400w, https://robocrop.realpython.net/?url=https%3A//files.realpython.com/media/gahjelle.470149ee709e.jpg&w=800&h=800&mode=crop&sig=e9b761c6cf1359953014dba05554f5424eb116e1 800w" sizes="(min-width: 1200px) 140px, calc(-1.5vw + 137px)" alt="Geir Arne Hjelle"/><p>
|
||||
Geir Arne is an avid Pythonista and a member of the Real Python tutorial team.
|
||||
</p></div>
|
||||
19547
packages/readabilityjs/test/test-pages/realpython/expected-metadata.json
Normal file
19547
packages/readabilityjs/test/test-pages/realpython/expected-metadata.json
Normal file
File diff suppressed because it is too large
Load diff
1568
packages/readabilityjs/test/test-pages/realpython/expected.html
Normal file
1568
packages/readabilityjs/test/test-pages/realpython/expected.html
Normal file
File diff suppressed because it is too large
Load diff
4150
packages/readabilityjs/test/test-pages/realpython/source.html
Normal file
4150
packages/readabilityjs/test/test-pages/realpython/source.html
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1 @@
|
|||
https://realpython.com/python310-new-features/
|
||||
|
|
@ -7,17 +7,17 @@ describe('isOldItem', () => {
|
|||
const item = {
|
||||
pubDate: '2020-01-01',
|
||||
} as RssFeedItem
|
||||
const lastFetchedAt = Date.now()
|
||||
const mostRecentItemTimestamp = Date.now()
|
||||
|
||||
expect(isOldItem(item, lastFetchedAt)).to.be.true
|
||||
expect(isOldItem(item, mostRecentItemTimestamp)).to.be.true
|
||||
})
|
||||
|
||||
it('returns true if item was published at the last fetched time', () => {
|
||||
const lastFetchedAt = Date.now()
|
||||
const mostRecentItemTimestamp = Date.now()
|
||||
const item = {
|
||||
pubDate: new Date(lastFetchedAt).toISOString(),
|
||||
pubDate: new Date(mostRecentItemTimestamp).toISOString(),
|
||||
} as RssFeedItem
|
||||
|
||||
expect(isOldItem(item, lastFetchedAt)).to.be.true
|
||||
expect(isOldItem(item, mostRecentItemTimestamp)).to.be.true
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ export const setLabels = async (
|
|||
})
|
||||
|
||||
try {
|
||||
return axios.post(`${apiEndpoint}/graphql`, data, {
|
||||
return await axios.post(`${apiEndpoint}/graphql`, data, {
|
||||
headers: {
|
||||
Cookie: `auth=${auth};`,
|
||||
'Content-Type': 'application/json',
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ export const sendNotification = async (
|
|||
}
|
||||
|
||||
try {
|
||||
return axios.post(`${apiEndpoint}/notification/send`, requestData, {
|
||||
return await axios.post(`${apiEndpoint}/notification/send`, requestData, {
|
||||
headers: {
|
||||
Cookie: `auth=${auth};`,
|
||||
'Content-Type': 'application/json',
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ export const archivePage = async (
|
|||
})
|
||||
|
||||
try {
|
||||
return axios.post(`${apiEndpoint}/graphql`, data, {
|
||||
return await axios.post(`${apiEndpoint}/graphql`, data, {
|
||||
headers: {
|
||||
Cookie: `auth=${auth};`,
|
||||
'Content-Type': 'application/json',
|
||||
|
|
@ -66,7 +66,7 @@ export const markPageAsRead = async (
|
|||
})
|
||||
|
||||
try {
|
||||
return axios.post(`${apiEndpoint}/graphql`, data, {
|
||||
return await axios.post(`${apiEndpoint}/graphql`, data, {
|
||||
headers: {
|
||||
Cookie: `auth=${auth};`,
|
||||
'Content-Type': 'application/json',
|
||||
|
|
|
|||
|
|
@ -78,6 +78,13 @@ export function HighlightNoteModal(
|
|||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
|
||||
event.preventDefault()
|
||||
saveNoteChanges()
|
||||
props.onOpenChange(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
|
|
|
|||
|
|
@ -169,7 +169,7 @@ export const { styled, css, theme, getCssText, globalCss, keyframes, config } =
|
|||
thBackground3: '#FFFFFF',
|
||||
thBackground4: '#EBEBEB',
|
||||
thBackground5: '#F5F5F5',
|
||||
thBackgroundActive: '#F9F9F9',
|
||||
thBackgroundActive: '#FFEA9F',
|
||||
thBackgroundContrast: '#FFFFFF',
|
||||
thLeftMenuBackground: '#FCFCFC',
|
||||
thLibraryBackground: '#F3F3F3',
|
||||
|
|
@ -281,7 +281,7 @@ const darkThemeSpec = {
|
|||
thBackground3: '#242424',
|
||||
thBackground4: '#3D3D3D',
|
||||
thBackground5: '#3D3D3D',
|
||||
thBackgroundActive: '#2E2E2E',
|
||||
thBackgroundActive: '#3D3D3D',
|
||||
thBackgroundContrast: '#000000',
|
||||
thLeftMenuBackground: '#1D1D1D',
|
||||
thLibraryBackground: '#333333',
|
||||
|
|
|
|||
|
|
@ -105,8 +105,8 @@ const run = async () => {
|
|||
serverAdapter.getRouter()
|
||||
)
|
||||
|
||||
app.listen(8080, () => {
|
||||
console.log('Running on 8080...')
|
||||
app.listen(process.env.PORT ?? 8080, () => {
|
||||
console.log(`Running on ${process.env.PORT ?? 8080}...`)
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@bull-board/express": "^3.10.4",
|
||||
"@bull-board/express": "^5.9.0",
|
||||
"body-parser": "^1.20.2",
|
||||
"bullmq": "^4.6.0",
|
||||
"connect-ensure-login": "^0.1.1",
|
||||
|
|
|
|||
|
|
@ -2,29 +2,29 @@
|
|||
# yarn lockfile v1
|
||||
|
||||
|
||||
"@bull-board/api@3.11.1":
|
||||
version "3.11.1"
|
||||
resolved "https://registry.npmjs.org/@bull-board/api/-/api-3.11.1.tgz"
|
||||
integrity sha512-ElwX7sM+Ng4ZL9KUsbDubRE+r2hu/gss85OsROeE9bmyfkW14jOJkgr5MKUyjTTgPEeMs1Mw55TgQs2vxoWBiA==
|
||||
"@bull-board/api@5.13.0":
|
||||
version "5.13.0"
|
||||
resolved "https://registry.yarnpkg.com/@bull-board/api/-/api-5.13.0.tgz#119dcb675555537b9a90d59294a3c093b02afac7"
|
||||
integrity sha512-v5wvnGim1pmSK9PR1RYSx1dsCW6sOQYJnpvRgU6HZbVbW/5Z0luUBGpYYxM2Ry98uYKeU999mbS7xjunOkAQDw==
|
||||
dependencies:
|
||||
redis-info "^3.0.8"
|
||||
|
||||
"@bull-board/express@^3.10.4":
|
||||
version "3.11.1"
|
||||
resolved "https://registry.npmjs.org/@bull-board/express/-/express-3.11.1.tgz"
|
||||
integrity sha512-+a5IQilu/CxvnGC0z6oJPANn7eF/Q61VU86JR9vRtmaY96mKKny0NuAyulJ2/Y9JznMCBOLUsXWL6fm9zD9kJw==
|
||||
"@bull-board/express@^5.9.0":
|
||||
version "5.13.0"
|
||||
resolved "https://registry.yarnpkg.com/@bull-board/express/-/express-5.13.0.tgz#29f2c0a61d6206c13e8816b9d0f79bf06c92064f"
|
||||
integrity sha512-KWI+nGLkZ1rLsOnjHvR7DdeP371l9Fr7narG0ygn78pybR5vAdcHXWde0Uusmm80JyM0nN1JOiqrhMp3mJH7NA==
|
||||
dependencies:
|
||||
"@bull-board/api" "3.11.1"
|
||||
"@bull-board/ui" "3.11.1"
|
||||
ejs "3.1.7"
|
||||
express "4.17.3"
|
||||
"@bull-board/api" "5.13.0"
|
||||
"@bull-board/ui" "5.13.0"
|
||||
ejs "^3.1.7"
|
||||
express "^4.17.3"
|
||||
|
||||
"@bull-board/ui@3.11.1":
|
||||
version "3.11.1"
|
||||
resolved "https://registry.npmjs.org/@bull-board/ui/-/ui-3.11.1.tgz"
|
||||
integrity sha512-SRrfvxHF/WaBICiAFuWAoAlTvoBYUBmX94oRbSKzVILRFZMe3gs0hN071BFohrn4yOTFHAkWPN7cjMbaqHwCag==
|
||||
"@bull-board/ui@5.13.0":
|
||||
version "5.13.0"
|
||||
resolved "https://registry.yarnpkg.com/@bull-board/ui/-/ui-5.13.0.tgz#b0f1a5a0e446c608b4c6c29bb5d866c05c9c8bd7"
|
||||
integrity sha512-UZ88j0c/G/UI5+F3zh6If9LqgF4kMmvRmTgnNckm8HJbclUdqvrcHBpo/e0HfdCaWGGhI2Gc12hq+AECc6c4Sw==
|
||||
dependencies:
|
||||
"@bull-board/api" "3.11.1"
|
||||
"@bull-board/api" "5.13.0"
|
||||
|
||||
"@ioredis/commands@^1.1.1":
|
||||
version "1.2.0"
|
||||
|
|
@ -96,22 +96,6 @@ balanced-match@^1.0.0:
|
|||
resolved "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz"
|
||||
integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==
|
||||
|
||||
body-parser@1.19.2:
|
||||
version "1.19.2"
|
||||
resolved "https://registry.npmjs.org/body-parser/-/body-parser-1.19.2.tgz"
|
||||
integrity sha512-SAAwOxgoCKMGs9uUAUFHygfLAyaniaoun6I8mFY9pRAJL9+Kec34aU+oIjDhTycub1jozEfEwx1W1IuOYxVSFw==
|
||||
dependencies:
|
||||
bytes "3.1.2"
|
||||
content-type "~1.0.4"
|
||||
debug "2.6.9"
|
||||
depd "~1.1.2"
|
||||
http-errors "1.8.1"
|
||||
iconv-lite "0.4.24"
|
||||
on-finished "~2.3.0"
|
||||
qs "6.9.7"
|
||||
raw-body "2.4.3"
|
||||
type-is "~1.6.18"
|
||||
|
||||
body-parser@1.20.1:
|
||||
version "1.20.1"
|
||||
resolved "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz"
|
||||
|
|
@ -294,30 +278,20 @@ depd@2.0.0, depd@~2.0.0:
|
|||
resolved "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz"
|
||||
integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==
|
||||
|
||||
depd@~1.1.2:
|
||||
version "1.1.2"
|
||||
resolved "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz"
|
||||
integrity sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==
|
||||
|
||||
destroy@1.2.0:
|
||||
version "1.2.0"
|
||||
resolved "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz"
|
||||
integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==
|
||||
|
||||
destroy@~1.0.4:
|
||||
version "1.0.4"
|
||||
resolved "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz"
|
||||
integrity sha512-3NdhDuEXnfun/z7x9GOElY49LoqVHoGScmOKwmxhsS8N5Y+Z8KyPPDnaSzqWgYt/ji4mqwfTS34Htrk0zPIXVg==
|
||||
|
||||
ee-first@1.1.1:
|
||||
version "1.1.1"
|
||||
resolved "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz"
|
||||
integrity sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==
|
||||
|
||||
ejs@3.1.7:
|
||||
version "3.1.7"
|
||||
resolved "https://registry.npmjs.org/ejs/-/ejs-3.1.7.tgz"
|
||||
integrity sha512-BIar7R6abbUxDA3bfXrO4DSgwo8I+fB5/1zgujl3HLLjwd6+9iOnrT+t3grn2qbk9vOgBubXOFwX2m9axoFaGw==
|
||||
ejs@^3.1.7:
|
||||
version "3.1.9"
|
||||
resolved "https://registry.yarnpkg.com/ejs/-/ejs-3.1.9.tgz#03c9e8777fe12686a9effcef22303ca3d8eeb361"
|
||||
integrity sha512-rC+QVNMJWv+MtPgkt0y+0rVEIdbtxVADApW9JXrUVlzHetgcyczP/E7DJmWJ4fJCZF2cPcBk0laWO9ZHMG3DmQ==
|
||||
dependencies:
|
||||
jake "^10.8.5"
|
||||
|
||||
|
|
@ -350,42 +324,6 @@ express-session@^1.17.2:
|
|||
safe-buffer "5.2.1"
|
||||
uid-safe "~2.1.5"
|
||||
|
||||
express@4.17.3:
|
||||
version "4.17.3"
|
||||
resolved "https://registry.npmjs.org/express/-/express-4.17.3.tgz"
|
||||
integrity sha512-yuSQpz5I+Ch7gFrPCk4/c+dIBKlQUxtgwqzph132bsT6qhuzss6I8cLJQz7B3rFblzd6wtcI0ZbGltH/C4LjUg==
|
||||
dependencies:
|
||||
accepts "~1.3.8"
|
||||
array-flatten "1.1.1"
|
||||
body-parser "1.19.2"
|
||||
content-disposition "0.5.4"
|
||||
content-type "~1.0.4"
|
||||
cookie "0.4.2"
|
||||
cookie-signature "1.0.6"
|
||||
debug "2.6.9"
|
||||
depd "~1.1.2"
|
||||
encodeurl "~1.0.2"
|
||||
escape-html "~1.0.3"
|
||||
etag "~1.8.1"
|
||||
finalhandler "~1.1.2"
|
||||
fresh "0.5.2"
|
||||
merge-descriptors "1.0.1"
|
||||
methods "~1.1.2"
|
||||
on-finished "~2.3.0"
|
||||
parseurl "~1.3.3"
|
||||
path-to-regexp "0.1.7"
|
||||
proxy-addr "~2.0.7"
|
||||
qs "6.9.7"
|
||||
range-parser "~1.2.1"
|
||||
safe-buffer "5.2.1"
|
||||
send "0.17.2"
|
||||
serve-static "1.14.2"
|
||||
setprototypeof "1.2.0"
|
||||
statuses "~1.5.0"
|
||||
type-is "~1.6.18"
|
||||
utils-merge "1.0.1"
|
||||
vary "~1.1.2"
|
||||
|
||||
express@^4.17.3:
|
||||
version "4.18.2"
|
||||
resolved "https://registry.npmjs.org/express/-/express-4.18.2.tgz"
|
||||
|
|
@ -443,19 +381,6 @@ finalhandler@1.2.0:
|
|||
statuses "2.0.1"
|
||||
unpipe "~1.0.0"
|
||||
|
||||
finalhandler@~1.1.2:
|
||||
version "1.1.2"
|
||||
resolved "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz"
|
||||
integrity sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==
|
||||
dependencies:
|
||||
debug "2.6.9"
|
||||
encodeurl "~1.0.2"
|
||||
escape-html "~1.0.3"
|
||||
on-finished "~2.3.0"
|
||||
parseurl "~1.3.3"
|
||||
statuses "~1.5.0"
|
||||
unpipe "~1.0.0"
|
||||
|
||||
forwarded@0.2.0:
|
||||
version "0.2.0"
|
||||
resolved "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz"
|
||||
|
|
@ -533,17 +458,6 @@ hasown@^2.0.0:
|
|||
dependencies:
|
||||
function-bind "^1.1.2"
|
||||
|
||||
http-errors@1.8.1:
|
||||
version "1.8.1"
|
||||
resolved "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz"
|
||||
integrity sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==
|
||||
dependencies:
|
||||
depd "~1.1.2"
|
||||
inherits "2.0.4"
|
||||
setprototypeof "1.2.0"
|
||||
statuses ">= 1.5.0 < 2"
|
||||
toidentifier "1.0.1"
|
||||
|
||||
http-errors@2.0.0:
|
||||
version "2.0.0"
|
||||
resolved "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz"
|
||||
|
|
@ -748,13 +662,6 @@ on-finished@2.4.1:
|
|||
dependencies:
|
||||
ee-first "1.1.1"
|
||||
|
||||
on-finished@~2.3.0:
|
||||
version "2.3.0"
|
||||
resolved "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz"
|
||||
integrity sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==
|
||||
dependencies:
|
||||
ee-first "1.1.1"
|
||||
|
||||
on-headers@~1.0.2:
|
||||
version "1.0.2"
|
||||
resolved "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz"
|
||||
|
|
@ -818,11 +725,6 @@ qs@6.11.0:
|
|||
dependencies:
|
||||
side-channel "^1.0.4"
|
||||
|
||||
qs@6.9.7:
|
||||
version "6.9.7"
|
||||
resolved "https://registry.npmjs.org/qs/-/qs-6.9.7.tgz"
|
||||
integrity sha512-IhMFgUmuNpyRfxA90umL7ByLlgRXu6tIfKPpF5TmcfRLlLCckfP/g3IQmju6jjpu+Hh8rA+2p6A27ZSPOOHdKw==
|
||||
|
||||
random-bytes@~1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz"
|
||||
|
|
@ -833,16 +735,6 @@ range-parser@~1.2.1:
|
|||
resolved "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz"
|
||||
integrity sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==
|
||||
|
||||
raw-body@2.4.3:
|
||||
version "2.4.3"
|
||||
resolved "https://registry.npmjs.org/raw-body/-/raw-body-2.4.3.tgz"
|
||||
integrity sha512-UlTNLIcu0uzb4D2f4WltY6cVjLi+/jEN4lgEUj3E04tpMDpUlkBo/eSn6zou9hum2VMNpCCUone0O0WeJim07g==
|
||||
dependencies:
|
||||
bytes "3.1.2"
|
||||
http-errors "1.8.1"
|
||||
iconv-lite "0.4.24"
|
||||
unpipe "1.0.0"
|
||||
|
||||
raw-body@2.5.1:
|
||||
version "2.5.1"
|
||||
resolved "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz"
|
||||
|
|
@ -907,25 +799,6 @@ semver@^7.5.4:
|
|||
dependencies:
|
||||
lru-cache "^6.0.0"
|
||||
|
||||
send@0.17.2:
|
||||
version "0.17.2"
|
||||
resolved "https://registry.npmjs.org/send/-/send-0.17.2.tgz"
|
||||
integrity sha512-UJYB6wFSJE3G00nEivR5rgWp8c2xXvJ3OPWPhmuteU0IKj8nKbG3DrjiOmLwpnHGYWAVwA69zmTm++YG0Hmwww==
|
||||
dependencies:
|
||||
debug "2.6.9"
|
||||
depd "~1.1.2"
|
||||
destroy "~1.0.4"
|
||||
encodeurl "~1.0.2"
|
||||
escape-html "~1.0.3"
|
||||
etag "~1.8.1"
|
||||
fresh "0.5.2"
|
||||
http-errors "1.8.1"
|
||||
mime "1.6.0"
|
||||
ms "2.1.3"
|
||||
on-finished "~2.3.0"
|
||||
range-parser "~1.2.1"
|
||||
statuses "~1.5.0"
|
||||
|
||||
send@0.18.0:
|
||||
version "0.18.0"
|
||||
resolved "https://registry.npmjs.org/send/-/send-0.18.0.tgz"
|
||||
|
|
@ -945,16 +818,6 @@ send@0.18.0:
|
|||
range-parser "~1.2.1"
|
||||
statuses "2.0.1"
|
||||
|
||||
serve-static@1.14.2:
|
||||
version "1.14.2"
|
||||
resolved "https://registry.npmjs.org/serve-static/-/serve-static-1.14.2.tgz"
|
||||
integrity sha512-+TMNA9AFxUEGuC0z2mevogSnn9MXKb4fa7ngeRMJaaGv8vTwnIEkKi+QGvPt33HSnf8pRS+WGM0EbMtCJLKMBQ==
|
||||
dependencies:
|
||||
encodeurl "~1.0.2"
|
||||
escape-html "~1.0.3"
|
||||
parseurl "~1.3.3"
|
||||
send "0.17.2"
|
||||
|
||||
serve-static@1.15.0:
|
||||
version "1.15.0"
|
||||
resolved "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz"
|
||||
|
|
@ -999,11 +862,6 @@ statuses@2.0.1:
|
|||
resolved "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz"
|
||||
integrity sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==
|
||||
|
||||
"statuses@>= 1.5.0 < 2", statuses@~1.5.0:
|
||||
version "1.5.0"
|
||||
resolved "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz"
|
||||
integrity sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==
|
||||
|
||||
strip-bom@^4.0.0:
|
||||
version "4.0.0"
|
||||
resolved "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz"
|
||||
|
|
|
|||
Loading…
Reference in a new issue