text
stringlengths 1
2.83M
| id
stringlengths 16
152
| metadata
dict | __index_level_0__
int64 0
949
|
---|---|---|---|
export * from './types'
export * from './useActiveApp'
export * from './useFileRouteReplace'
export * from './useRoute'
export * from './useRouteName'
export * from './useRouteMeta'
export * from './useRouteParam'
export * from './useRouteQuery'
export * from './useRouteQueryPersisted'
export * from './useRouter'
export * from './useActiveLocation'
| owncloud/web/packages/web-pkg/src/composables/router/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/router/index.ts",
"repo_id": "owncloud",
"token_count": 111
} | 851 |
import { computed, unref } from 'vue'
import { SearchResult } from '../../components'
import { DavProperties } from '@ownclouders/web-client/src/webdav'
import { urlJoin } from '@ownclouders/web-client/src/utils'
import { useClientService } from '../clientService'
import { isProjectSpaceResource } from '@ownclouders/web-client/src/helpers'
import { useConfigStore, useResourcesStore, useSpacesStore } from '../piniaStores'
import { SearchResource } from '@ownclouders/web-client/src/webdav/search'
export const useSearch = () => {
const configStore = useConfigStore()
const clientService = useClientService()
const spacesStore = useSpacesStore()
const resourcesStore = useResourcesStore()
const areHiddenFilesShown = computed(() => resourcesStore.areHiddenFilesShown)
const projectSpaces = computed(() => spacesStore.spaces.filter(isProjectSpaceResource))
const getProjectSpace = (id: string) => {
return unref(projectSpaces).find((s) => s.id === id)
}
const search = async (term: string, searchLimit = null): Promise<SearchResult> => {
if (configStore.options.routing.fullShareOwnerPaths) {
await spacesStore.loadMountPoints({ graphClient: clientService.graphAuthenticated })
}
if (!term) {
return {
totalResults: null,
values: []
}
}
const { resources, totalResults } = await clientService.webdav.search(term, {
searchLimit,
davProperties: DavProperties.Default
})
return {
totalResults,
values: resources
.map((resource) => {
const matchingSpace = getProjectSpace(resource.parentFolderId)
const data = (matchingSpace ? matchingSpace : resource) as SearchResource
if (configStore.options.routing.fullShareOwnerPaths && data.shareRoot) {
data.path = urlJoin(data.shareRoot, data.path)
}
return { id: data.id, data }
})
.filter(({ data }) => {
// filter results if hidden files shouldn't be shown due to settings
return !data.name.startsWith('.') || unref(areHiddenFilesShown)
})
}
}
return {
search
}
}
export type SearchFunction = ReturnType<typeof useSearch>['search']
| owncloud/web/packages/web-pkg/src/composables/search/useSearch.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/search/useSearch.ts",
"repo_id": "owncloud",
"token_count": 784
} | 852 |
import { useGettext } from 'vue3-gettext'
export const useSpaceHelpers = () => {
const { $gettext } = useGettext()
const checkSpaceNameModalInput = (name: string, setError: (value: string) => void) => {
if (name.trim() === '') {
return setError($gettext('Space name cannot be empty'))
}
if (name.length > 255) {
return setError($gettext('Space name cannot exceed 255 characters'))
}
if (/[/\\.:?*"><|]/.test(name)) {
return setError(
$gettext('Space name cannot contain the following characters: / \\\\ . : ? * " > < |\'')
)
}
return setError(null)
}
return { checkSpaceNameModalInput }
}
| owncloud/web/packages/web-pkg/src/composables/spaces/useSpaceHelpers.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/composables/spaces/useSpaceHelpers.ts",
"repo_id": "owncloud",
"token_count": 251
} | 853 |
import { DateTime } from 'luxon'
import { getLocaleFromLanguage } from './locale'
export const formatDateFromDateTime = (
date: DateTime,
currentLanguage: string,
format = DateTime.DATETIME_MED
) => {
return date.setLocale(getLocaleFromLanguage(currentLanguage)).toLocaleString(format)
}
export const formatDateFromJSDate = (
date: Date,
currentLanguage: string,
format = DateTime.DATETIME_MED
) => {
return formatDateFromDateTime(DateTime.fromJSDate(date), currentLanguage, format)
}
export const formatDateFromHTTP = (
date: string,
currentLanguage: string,
format = DateTime.DATETIME_MED
) => {
return formatDateFromDateTime(DateTime.fromHTTP(date), currentLanguage, format)
}
export const formatDateFromISO = (
date: string,
currentLanguage,
format = DateTime.DATETIME_MED
) => {
return formatDateFromDateTime(DateTime.fromISO(date), currentLanguage, format)
}
export const formatDateFromRFC = (
date: string,
currentLanguage: string,
format = DateTime.DATETIME_MED
) => {
return formatDateFromDateTime(DateTime.fromRFC2822(date), currentLanguage, format)
}
export const formatRelativeDateFromDateTime = (date: DateTime, currentLanguage: string) => {
return date.setLocale(getLocaleFromLanguage(currentLanguage)).toRelative()
}
export const formatRelativeDateFromJSDate = (date: Date, currentLanguage: string) => {
return formatRelativeDateFromDateTime(DateTime.fromJSDate(date), currentLanguage)
}
export const formatRelativeDateFromHTTP = (date: string, currentLanguage: string) => {
return formatRelativeDateFromDateTime(DateTime.fromHTTP(date), currentLanguage)
}
export const formatRelativeDateFromISO = (date: string, currentLanguage: string) => {
return formatRelativeDateFromDateTime(DateTime.fromISO(date), currentLanguage)
}
export const formatRelativeDateFromRFC = (date: string, currentLanguage: string) => {
return formatRelativeDateFromDateTime(DateTime.fromRFC2822(date), currentLanguage)
}
| owncloud/web/packages/web-pkg/src/helpers/datetime.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/datetime.ts",
"repo_id": "owncloud",
"token_count": 589
} | 854 |
export type IconFillType = 'fill' | 'line' | 'none'
export type IconType = {
name: string
color?: string
fillType?: IconFillType
}
export type ResourceIconMapping = Record<'mimeType' | 'extension', Record<string, IconType>>
export const resourceIconMappingInjectionKey = 'oc-resource-icon-mapping'
const fileIcon = {
archive: {
icon: { name: 'resource-type-archive', color: 'var(--oc-color-icon-archive)' },
extensions: [
'7z',
'apk',
'bz2',
'deb',
'gz',
'gzip',
'rar',
'tar',
'tar.bz2',
'tar.gz',
'tar.xz',
'tbz2',
'tgz',
'zip'
]
},
audio: {
icon: { name: 'resource-type-audio', color: 'var(--oc-color-icon-audio)' },
extensions: [
'3gp',
'8svx',
'aa',
'aac',
'aax',
'act',
'aiff',
'alac',
'amr',
'ape',
'au',
'awb',
'cda',
'dss',
'dvf',
'flac',
'gsm',
'iklax',
'ivs',
'm4a',
'm4b',
'm4p',
'mmf',
'mogg',
'movpkg',
'mp3',
'mpc',
'msv',
'nmf',
'oga',
'ogga',
'opus',
'ra',
'raw',
'rf64',
'rm',
'sln',
'tta',
'voc',
'vox',
'wav',
'wma',
'wv'
]
},
code: {
icon: { name: 'resource-type-code', color: 'var(--oc-color-text-default)' },
extensions: [
'bash',
'c++',
'c',
'cc',
'cpp',
'css',
'feature',
'go',
'h',
'hh',
'hpp',
'htm',
'html',
'java',
'js',
'json',
'php',
'pl',
'py',
'scss',
'sh',
'sh-lib',
'sql',
'ts',
'xml',
'yaml',
'yml'
]
},
default: {
icon: { name: 'resource-type-file', color: 'var(--oc-color-text-default)' },
extensions: ['accdb', 'rss', 'swf']
},
drawio: {
icon: { name: 'resource-type-drawio', color: 'var(--oc-color-icon-drawio)' },
extensions: ['drawio']
},
document: {
icon: { name: 'resource-type-document', color: 'var(--oc-color-icon-document)' },
extensions: ['doc', 'docm', 'docx', 'dot', 'dotx', 'lwp', 'odt', 'one', 'vsd', 'wpd']
},
ifc: {
icon: { name: 'resource-type-ifc', color: 'var(--oc-color-icon-ifc)' },
extensions: ['ifc']
},
ipynb: {
icon: { name: 'resource-type-jupyter', color: 'var(--oc-color-icon-jupyter)' },
extensions: ['ipynb']
},
image: {
icon: { name: 'resource-type-image', color: 'var(--oc-color-icon-image)' },
extensions: [
'ai',
'cdr',
'eot',
'eps',
'gif',
'jpeg',
'jpg',
'otf',
'pfb',
'png',
'ps',
'psd',
'svg',
'ttf',
'woff',
'xcf'
]
},
form: {
icon: { name: 'resource-type-form', color: 'var(--oc-color-icon-form)' },
extensions: ['docf', 'docxf', 'oform']
},
markdown: {
icon: { name: 'resource-type-markdown', color: 'var(--oc-color-icon-markdown)' },
extensions: ['md', 'markdown']
},
odg: {
icon: { name: 'resource-type-graphic', color: 'var(--oc-color-icon-graphic)' },
extensions: ['odg']
},
pdf: {
icon: { name: 'resource-type-pdf', color: 'var(--oc-color-icon-pdf)' },
extensions: ['pdf']
},
presentation: {
icon: { name: 'resource-type-presentation', color: 'var(--oc-color-icon-presentation)' },
extensions: [
'odp',
'pot',
'potm',
'potx',
'ppa',
'ppam',
'pps',
'ppsm',
'ppsx',
'ppt',
'pptm',
'pptx'
]
},
root: {
icon: { name: 'resource-type-root', color: 'var(--oc-color-icon-root)' },
extensions: ['root']
},
spreadsheet: {
icon: { name: 'resource-type-spreadsheet', color: 'var(--oc-color-icon-spreadsheet)' },
extensions: ['csv', 'ods', 'xla', 'xlam', 'xls', 'xlsb', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx']
},
text: {
icon: { name: 'resource-type-text', color: 'var(--oc-color-text-default)' },
extensions: ['cb7', 'cba', 'cbr', 'cbt', 'cbtc', 'cbz', 'cvbdl', 'eml', 'mdb', 'tex', 'txt']
},
url: {
icon: { name: 'resource-type-url', color: 'var(--oc-color-text-default)' },
extensions: ['url']
},
video: {
icon: {
name: 'resource-type-video',
color: 'var(--oc-color-icon-video)'
},
extensions: ['mov', 'mp4', 'webm', 'wmv']
},
epub: {
icon: { name: 'resource-type-book', color: 'var(--oc-color-icon-epub)' },
extensions: ['epub']
}
}
export function createDefaultFileIconMapping() {
const fileIconMapping: Record<string, IconType> = {}
Object.values(fileIcon).forEach((value) => {
value.extensions.forEach((extension) => {
fileIconMapping[extension] = value.icon
})
})
return fileIconMapping
}
| owncloud/web/packages/web-pkg/src/helpers/resource/icon.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/helpers/resource/icon.ts",
"repo_id": "owncloud",
"token_count": 2466
} | 855 |
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, CancelTokenSource } from 'axios'
import merge from 'lodash-es/merge'
import { z } from 'zod'
export type RequestConfig<D, S> = AxiosRequestConfig<D> & {
schema?: S extends z.Schema ? S : never
}
export class HttpClient {
private readonly instance: AxiosInstance
private readonly cancelToken: CancelTokenSource
constructor(config?: AxiosRequestConfig) {
this.cancelToken = axios.CancelToken.source()
this.instance = axios.create(config)
}
public cancel(msg?: string): void {
this.cancelToken.cancel(msg)
}
public async delete<T = any, D = any, S extends z.Schema | T = T>(
url: string,
data?: D,
config?: RequestConfig<D, S>
) {
return await this.internalRequestWithData('delete', url, data, config)
}
public get<T = unknown, D = any, S extends z.Schema | T = T>(
url: string,
config?: RequestConfig<D, S>
) {
return this.internalRequest('get', url, config)
}
public head<T = any, D = any, S extends z.Schema | T = T>(
url: string,
config?: RequestConfig<D, S>
) {
return this.internalRequest('head', url, config)
}
public options<T = any, D = any, S extends z.Schema | T = T>(
url: string,
config?: RequestConfig<D, S>
) {
return this.internalRequest('options', url, config)
}
public patch<T = any, D = any, S extends z.Schema | T = T>(
url: string,
data?: D,
config?: RequestConfig<D, S>
) {
return this.internalRequestWithData('patch', url, data, config)
}
public post<T = any, D = any, S extends z.Schema | T = T>(
url: string,
data?: D,
config?: RequestConfig<D, S>
) {
return this.internalRequestWithData('post', url, data, config)
}
public put<T = any, D = any, S extends z.Schema | T = T>(
url: string,
data?: D,
config?: RequestConfig<D, S>
) {
return this.internalRequestWithData('put', url, data, config)
}
public async request<T = any, D = any, S extends z.Schema | T = T>(config: RequestConfig<D, S>) {
const response = await this.instance.request<S, AxiosResponse<S>, D>(
this.obtainConfig<D>(config)
)
return this.processResponse(response, config)
}
private obtainConfig<D = any>(config?: AxiosRequestConfig): AxiosRequestConfig<D> {
return merge({ cancelToken: this.cancelToken.token }, config)
}
private processResponse<T, S extends z.Schema | T = T>(
response: AxiosResponse<T>,
config?: RequestConfig<any, S>
): AxiosResponse<S extends z.Schema ? z.infer<S> : T> {
if (config?.schema) {
const data = config.schema.parse(response.data)
return { ...response, data } as AxiosResponse<S extends z.Schema ? z.infer<S> : T>
}
return response as AxiosResponse<S extends z.Schema ? z.infer<S> : T>
}
private async internalRequest<T = any, D = any, S extends z.Schema | T = T>(
method: 'delete' | 'get' | 'head' | 'options',
url: string,
config: RequestConfig<D, S>
) {
const response = await this.instance[method]<S, AxiosResponse<S>, D>(
url,
this.obtainConfig<D>(config)
)
return this.processResponse(response, config)
}
private async internalRequestWithData<T = any, D = any, S extends z.Schema | T = T>(
method: 'post' | 'put' | 'patch' | 'delete',
url: string,
data: D,
config: RequestConfig<D, S>
) {
const response = await this.instance[method]<S, AxiosResponse<S>, D>(
url,
data,
this.obtainConfig<D>(config)
)
return this.processResponse(response, config)
}
}
| owncloud/web/packages/web-pkg/src/http/client.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/http/client.ts",
"repo_id": "owncloud",
"token_count": 1345
} | 856 |
export interface AuthParameters {
accessToken?: string
publicLinkToken?: string
publicLinkPassword?: string
}
export class Auth {
accessToken?: string
publicLinkToken?: string
publicLinkPassword?: string
constructor(params: AuthParameters = {}) {
this.accessToken = params.accessToken
this.publicLinkToken = params.publicLinkToken
this.publicLinkPassword = params.publicLinkPassword
}
getHeaders(): any {
return {
...(this.publicLinkToken && { 'public-token': this.publicLinkToken }),
...(this.publicLinkPassword && {
Authorization:
'Basic ' + Buffer.from(['public', this.publicLinkPassword].join(':')).toString('base64')
}),
...(this.accessToken && {
Authorization: 'Bearer ' + this.accessToken
})
}
}
}
| owncloud/web/packages/web-pkg/src/services/client/auth.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/services/client/auth.ts",
"repo_id": "owncloud",
"token_count": 274
} | 857 |
export * from './types'
| owncloud/web/packages/web-pkg/src/ui/index.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/src/ui/index.ts",
"repo_id": "owncloud",
"token_count": 8
} | 858 |
import { PartialComponentProps, defaultPlugins, mount } from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { Resource } from '@ownclouders/web-client/src/helpers'
import BatchActions from '../../../src/components/BatchActions.vue'
import { Action, ActionMenuItem } from '../../../src'
const selectors = {
actionMenuItemStub: 'action-menu-item-stub',
batchActionsSquashed: '.oc-appbar-batch-actions-squashed'
}
describe('BatchActions', () => {
describe('menu sections', () => {
it('do not render when no action enabled', () => {
const { wrapper } = getWrapper()
expect(wrapper.findAll(selectors.actionMenuItemStub).length).toBe(0)
})
it('render enabled actions', () => {
const actions = [{} as Action]
const { wrapper } = getWrapper({ props: { actions } })
expect(wrapper.findAll(selectors.actionMenuItemStub).length).toBe(actions.length)
})
})
describe('limited screen space', () => {
it('adds the squashed-class when limited screen space is available', () => {
const { wrapper } = getWrapper({ props: { limitedScreenSpace: true } })
expect(wrapper.find(selectors.batchActionsSquashed).exists()).toBeTruthy()
})
it('correctly tells the action item component to show tooltips when limited screen space is available', () => {
const { wrapper } = getWrapper({
props: { actions: [{} as Action], limitedScreenSpace: true }
})
expect(
wrapper.findComponent<typeof ActionMenuItem>(selectors.actionMenuItemStub).props()
.showTooltip
).toBeTruthy()
})
})
})
function getWrapper(
{ props }: { props?: PartialComponentProps<typeof BatchActions> } = { props: {} }
) {
return {
wrapper: mount(BatchActions, {
props: {
items: [mock<Resource>()],
actions: [],
actionOptions: {},
...props
},
global: {
stubs: { 'action-menu-item': true },
plugins: [...defaultPlugins()]
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/BatchActions.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/BatchActions.spec.ts",
"repo_id": "owncloud",
"token_count": 759
} | 859 |
import { useRouteQuery } from '../../../src/composables/router/useRouteQuery'
import SearchBarFilter from '../../../src/components/SearchBarFilter.vue'
import { defaultComponentMocks, defaultPlugins, shallowMount } from 'web-test-helpers'
import { OcFilterChip } from 'design-system/src/components'
vi.mock('../../../src/composables/router/useRouteQuery')
const selectors = {
filterChipStub: 'oc-filter-chip-stub'
}
describe('SearchBarFilter', () => {
it('shows "All files" as default option', () => {
const { wrapper } = getWrapper({ currentFolderAvailable: true })
const filterLabel = wrapper
.findComponent<typeof OcFilterChip>(selectors.filterChipStub)
.props('filterLabel')
expect(filterLabel).toBe('All files')
})
it('shows "All files" as current option if no Current folder available', () => {
const { wrapper } = getWrapper()
const filterLabel = wrapper
.findComponent<typeof OcFilterChip>(selectors.filterChipStub)
.props('filterLabel')
expect(filterLabel).toBe('All files')
})
it('shows "Current folder" as current option if given via scope', () => {
const { wrapper } = getWrapper({ useScope: 'true' })
const filterLabel = wrapper
.findComponent<typeof OcFilterChip>(selectors.filterChipStub)
.props('filterLabel')
expect(filterLabel).toBe('Current folder')
})
})
function getWrapper({ currentFolderAvailable = false, useScope = null } = {}) {
vi.mocked(useRouteQuery).mockImplementationOnce(() => useScope)
const mocks = defaultComponentMocks()
return {
mocks,
wrapper: shallowMount(SearchBarFilter, {
props: {
currentFolderAvailable
},
global: {
plugins: [...defaultPlugins()],
mocks,
provide: mocks
}
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/components/SearchBarFilter.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/components/SearchBarFilter.spec.ts",
"repo_id": "owncloud",
"token_count": 630
} | 860 |
import { mock } from 'vitest-mock-extended'
import { unref } from 'vue'
import { useFileActionsEnableSync } from '../../../../../src/composables/actions/files/useFileActionsEnableSync'
import { IncomingShareResource } from '@ownclouders/web-client/src/helpers/share'
import { defaultComponentMocks, getComposableWrapper, RouteLocation } from 'web-test-helpers'
const sharesWithMeLocation = 'files-shares-with-me'
const sharesWithOthersLocation = 'files-shares-with-others'
describe('acceptShare', () => {
describe('computed property "actions"', () => {
describe('isVisible property of returned element', () => {
it.each([
{ resources: [{ syncEnabled: false }] as IncomingShareResource[], expectedStatus: true },
{ resources: [{ syncEnabled: true }] as IncomingShareResource[], expectedStatus: false }
])(
`should be set according to the resource syncEnabled state if the route name is "${sharesWithMeLocation}"`,
(inputData) => {
getWrapper({
setup: () => {
const { actions } = useFileActionsEnableSync()
const resources = inputData.resources
expect(unref(actions)[0].isVisible({ space: null, resources })).toBe(
inputData.expectedStatus
)
}
})
}
)
it.each([
{ syncEnabled: false } as IncomingShareResource,
{ syncEnabled: true } as IncomingShareResource
])(
`should be set as false if the route name is other than "${sharesWithMeLocation}"`,
(resource) => {
getWrapper({
routeName: sharesWithOthersLocation,
setup: () => {
const { actions } = useFileActionsEnableSync()
expect(
unref(actions)[0].isVisible({ space: null, resources: [resource] })
).toBeFalsy()
}
})
}
)
})
})
})
function getWrapper({ setup, routeName = sharesWithMeLocation }) {
const mocks = defaultComponentMocks({ currentRoute: mock<RouteLocation>({ name: routeName }) })
return {
wrapper: getComposableWrapper(setup, {
mocks,
provide: mocks
})
}
}
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsAcceptShare.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsAcceptShare.spec.ts",
"repo_id": "owncloud",
"token_count": 905
} | 861 |
import { SideBarEventTopics, eventBus, useFileActionsShowDetails } from '../../../../../src'
import { defaultComponentMocks, getComposableWrapper } from 'web-test-helpers'
import { unref } from 'vue'
import { Resource } from '@ownclouders/web-client'
describe('showDetails', () => {
describe('handler', () => {
it('should trigger the open sidebar event', () => {
const mocks = defaultComponentMocks()
getComposableWrapper(
() => {
const { actions } = useFileActionsShowDetails()
const busStub = vi.spyOn(eventBus, 'publish')
const resources = [{ id: '1', path: '/folder' }] as Resource[]
unref(actions)[0].handler({ space: null, resources })
expect(busStub).toHaveBeenCalledWith(SideBarEventTopics.open)
},
{ mocks, provide: mocks }
)
})
})
})
| owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsShowDetails.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/actions/files/useFileActionsShowDetails.spec.ts",
"repo_id": "owncloud",
"token_count": 332
} | 862 |
import { useEmbedMode } from '../../../../src/composables/embedMode'
import { defaultComponentMocks, getComposableWrapper } from 'web-test-helpers'
import { unref } from 'vue'
describe('useEmbedMode', () => {
describe('isEnabled', () => {
it('when embed mode is disabled should return false', () => {
getComposableWrapper(
() => {
const { isEnabled } = useEmbedMode()
expect(unref(isEnabled)).toStrictEqual(false)
},
getWrapperOptions({ enabled: false })
)
})
it('when embed mode is enabled should return true', () => {
getComposableWrapper(
() => {
const { isEnabled } = useEmbedMode()
expect(unref(isEnabled)).toStrictEqual(true)
},
getWrapperOptions({ enabled: true })
)
})
})
describe('isLocationPicker', () => {
it('when target is not location should return false', () => {
getComposableWrapper(
() => {
const { isLocationPicker } = useEmbedMode()
expect(unref(isLocationPicker)).toStrictEqual(false)
},
getWrapperOptions({ target: 'resources' })
)
})
it('when target is location should return true', () => {
getComposableWrapper(
() => {
const { isLocationPicker } = useEmbedMode()
expect(unref(isLocationPicker)).toStrictEqual(true)
},
getWrapperOptions({ target: 'location' })
)
})
})
describe('messagesTargetOrigin', () => {
it('when messagesOrigin is set should return it', () => {
getComposableWrapper(
() => {
const { messagesTargetOrigin } = useEmbedMode()
expect(unref(messagesTargetOrigin)).toStrictEqual('message-origin')
},
getWrapperOptions({ messagesOrigin: 'message-origin' })
)
})
})
describe('isDelegatingAuthentication', () => {
it('when delegation is enabled but embed mode is not enabled should return false', () => {
getComposableWrapper(
() => {
const { isDelegatingAuthentication } = useEmbedMode()
expect(unref(isDelegatingAuthentication)).toStrictEqual(false)
},
getWrapperOptions({ enabled: false, delegateAuthentication: true })
)
})
it('when delegation is enabled and embed mode is enabled should return true', () => {
getComposableWrapper(
() => {
const { isDelegatingAuthentication } = useEmbedMode()
expect(unref(isDelegatingAuthentication)).toStrictEqual(true)
},
getWrapperOptions({ enabled: true, delegateAuthentication: true })
)
})
it('when delegation is disabled and embed mode is enabled should return false', () => {
getComposableWrapper(
() => {
const { isDelegatingAuthentication } = useEmbedMode()
expect(unref(isDelegatingAuthentication)).toStrictEqual(false)
},
getWrapperOptions({ enabled: false, delegateAuthentication: false })
)
})
})
describe('postMessage', () => {
it('when targetOrigin is not set should call postMessage without any origin', () => {
window.parent.postMessage = vi.fn() as (...args) => unknown
getComposableWrapper(
() => {
const { postMessage } = useEmbedMode()
postMessage('owncloud-embed:request-token', { hello: 'world' })
expect(window.parent.postMessage).toHaveBeenCalledWith(
{
name: 'owncloud-embed:request-token',
data: { hello: 'world' }
},
{}
)
},
getWrapperOptions({ messagesOrigin: undefined })
)
})
it('when targetOrigin is set should call postMessage with its value as origin', () => {
window.parent.postMessage = vi.fn() as (...args) => unknown
getComposableWrapper(
() => {
const { postMessage } = useEmbedMode()
postMessage('owncloud-embed:request-token', { hello: 'world' })
expect(window.parent.postMessage).toHaveBeenCalledWith(
{
name: 'owncloud-embed:request-token',
data: { hello: 'world' }
},
{ targetOrigin: 'messages-origin' }
)
},
getWrapperOptions({ messagesOrigin: 'messages-origin' })
)
})
})
describe('verifyDelegatedAuthenticationOrigin', () => {
it('when delegateAuthenticationOrigin is not set should return true', () => {
getComposableWrapper(
() => {
const { verifyDelegatedAuthenticationOrigin } = useEmbedMode()
expect(verifyDelegatedAuthenticationOrigin('event-origin')).toStrictEqual(true)
},
{ mocks: defaultComponentMocks() }
)
})
it('when delegateAuthenticationOrigin is set and origins match should return true', () => {
getComposableWrapper(
() => {
const { verifyDelegatedAuthenticationOrigin } = useEmbedMode()
expect(verifyDelegatedAuthenticationOrigin('event-origin')).toStrictEqual(true)
},
getWrapperOptions({ messagesOrigin: 'event-origin' })
)
})
it('when delegateAuthenticationOrigin is set but origins do not match should return false', () => {
getComposableWrapper(
() => {
const { verifyDelegatedAuthenticationOrigin } = useEmbedMode()
expect(verifyDelegatedAuthenticationOrigin('event-origin')).toStrictEqual(false)
},
getWrapperOptions({ delegateAuthenticationOrigin: 'authentication-origin' })
)
})
})
})
const getWrapperOptions = (embed = {}) => ({
mocks: defaultComponentMocks(),
pluginOptions: {
piniaOptions: {
configState: { options: { embed } }
}
}
})
| owncloud/web/packages/web-pkg/tests/unit/composables/embedMode/useEmbedMode.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/embedMode/useEmbedMode.spec.ts",
"repo_id": "owncloud",
"token_count": 2358
} | 863 |
import { EventBus } from '../../../../src/services/eventBus'
import { SideBarEventTopics, useSideBar } from '../../../../src/composables/sideBar'
import { unref, ref } from 'vue'
import { getComposableWrapper } from 'web-test-helpers'
vi.mock('../../../../src/composables/localStorage', async (importOriginal) => ({
useLocalStorage: () => ref(false)
}))
describe('useSideBar', () => {
let eventBus
beforeEach(() => {
eventBus = new EventBus()
})
describe('initial state', () => {
it('should have "isSideBarOpen" as "false"', () => {
getComposableWrapper(() => {
const { isSideBarOpen } = useSideBar({ bus: eventBus })
expect(unref(isSideBarOpen)).toBe(false)
})
})
it('should have "sideBarActivePanel" as "null"', () => {
getComposableWrapper(() => {
const { sideBarActivePanel } = useSideBar({ bus: eventBus })
expect(unref(sideBarActivePanel)).toBeNull()
})
})
})
describe('open', () => {
it('should set "isSideBarOpen" to "true"', () => {
getComposableWrapper(() => {
const { isSideBarOpen } = useSideBar({ bus: eventBus })
eventBus.publish(SideBarEventTopics.open)
expect(unref(isSideBarOpen)).toBe(true)
})
})
it('should set "sideBarActivePanel" to "null"', () => {
getComposableWrapper(() => {
const { sideBarActivePanel } = useSideBar({ bus: eventBus })
eventBus.publish(SideBarEventTopics.open)
expect(unref(sideBarActivePanel)).toBeNull()
})
})
})
describe('close', () => {
it('should set "isSideBarOpen" to "false"', () => {
getComposableWrapper(() => {
const { isSideBarOpen } = useSideBar({ bus: eventBus })
eventBus.publish(SideBarEventTopics.close)
expect(unref(isSideBarOpen)).toBe(false)
})
})
it('should set "sideBarActivePanel" to "null"', () => {
getComposableWrapper(() => {
const { sideBarActivePanel } = useSideBar({ bus: eventBus })
eventBus.publish(SideBarEventTopics.close)
expect(unref(sideBarActivePanel)).toBeNull()
})
})
})
describe('toggle', () => {
it('should toggle "isSideBarOpen" back and forth', () => {
getComposableWrapper(() => {
const { isSideBarOpen } = useSideBar({ bus: eventBus })
eventBus.publish(SideBarEventTopics.toggle)
expect(unref(isSideBarOpen)).toBe(true)
eventBus.publish(SideBarEventTopics.toggle)
expect(unref(isSideBarOpen)).toBe(false)
})
})
it('should not influence "sideBarActivePanel"', () => {
getComposableWrapper(() => {
const { sideBarActivePanel } = useSideBar({ bus: eventBus })
// initial state
eventBus.publish(SideBarEventTopics.toggle)
expect(unref(sideBarActivePanel)).toBe(null)
// modified active panel
eventBus.publish(SideBarEventTopics.setActivePanel, 'SomePanel')
eventBus.publish(SideBarEventTopics.toggle)
expect(unref(sideBarActivePanel)).toBe('SomePanel')
})
})
})
describe('openWithPanel', () => {
it('should set "isSideBarOpen" to "true"', () => {
getComposableWrapper(() => {
const { isSideBarOpen } = useSideBar({ bus: eventBus })
eventBus.publish(SideBarEventTopics.openWithPanel, 'SomePanel')
expect(unref(isSideBarOpen)).toBe(true)
})
})
it('should set "sideBarActivePanel" to provided value', () => {
getComposableWrapper(() => {
const { sideBarActivePanel } = useSideBar({ bus: eventBus })
eventBus.publish(SideBarEventTopics.openWithPanel, 'SomePanel')
expect(unref(sideBarActivePanel)).toBe('SomePanel')
})
})
})
describe('setActivePanel', () => {
it('should not influence "isSideBarOpen"', () => {
getComposableWrapper(() => {
const { isSideBarOpen } = useSideBar({ bus: eventBus })
expect(unref(isSideBarOpen)).toBe(false)
})
})
it('should set "sideBarActivePanel" to provided value', () => {
getComposableWrapper(() => {
const { sideBarActivePanel } = useSideBar({ bus: eventBus })
eventBus.publish(SideBarEventTopics.setActivePanel, 'SomePanel')
expect(unref(sideBarActivePanel)).toBe('SomePanel')
})
})
})
})
| owncloud/web/packages/web-pkg/tests/unit/composables/sideBar/useSideBar.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/composables/sideBar/useSideBar.spec.ts",
"repo_id": "owncloud",
"token_count": 1750
} | 864 |
import { Resource } from '@ownclouders/web-client/src'
import { isResourceTxtFileAlmostEmpty } from '../../../../src/helpers/resource'
describe('isResourceTxtFileAlmostEmpty', () => {
it('return true for resources smaller 30 bytes', () => {
expect(isResourceTxtFileAlmostEmpty({ mimeType: 'text/plain', size: 20 } as Resource)).toBe(
true
)
})
it('return false for resources larger 30 bytes', () => {
expect(isResourceTxtFileAlmostEmpty({ mimeType: 'text/plain', size: 35 } as Resource)).toBe(
false
)
})
it('return false for resources that are not text', () => {
expect(
isResourceTxtFileAlmostEmpty({ mimeType: 'application/json', size: 35 } as Resource)
).toBe(false)
})
it('return false for resources that have undefined mimeType', () => {
expect(isResourceTxtFileAlmostEmpty({ mimeType: undefined, size: 35 } as Resource)).toBe(false)
})
})
| owncloud/web/packages/web-pkg/tests/unit/helpers/resource/isResourceTxtFileAlmostEmpty.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/helpers/resource/isResourceTxtFileAlmostEmpty.ts",
"repo_id": "owncloud",
"token_count": 304
} | 865 |
import { objectKeys } from '../../../src/utils'
describe('objectKeys', () => {
it('should return the correct keys', () => {
expect(
objectKeys({
foo1: { bar1: { baz1: 1, baz2: 1 }, bar2: { baz1: 1, baz2: 1 }, bar3: 1 },
foo2: 1
})
).toMatchObject([
'foo1.bar1.baz1',
'foo1.bar1.baz2',
'foo1.bar2.baz1',
'foo1.bar2.baz2',
'foo1.bar3',
'foo2'
])
})
})
| owncloud/web/packages/web-pkg/tests/unit/utils/objectKeys.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-pkg/tests/unit/utils/objectKeys.spec.ts",
"repo_id": "owncloud",
"token_count": 232
} | 866 |
<template>
<li class="oc-sidebar-nav-item oc-pb-xs oc-px-s" :aria-current="active ? 'page' : null">
<oc-button
v-oc-tooltip="toolTip"
:type="handler ? 'button' : 'router-link'"
:appearance="active ? 'raw-inverse' : 'raw'"
:variation="active ? 'primary' : 'passive'"
:class="['oc-sidebar-nav-item-link', 'oc-oc-width-1-1', { active: active }]"
:data-nav-id="index"
:data-nav-name="navName"
v-bind="attrs"
>
<span class="oc-flex">
<oc-icon :name="icon" :fill-type="fillType" variation="inherit" />
<span class="oc-ml-m text" :class="{ 'text-invisible': collapsed }" v-text="name" />
</span>
</oc-button>
</li>
</template>
<script lang="ts">
import { computed, defineComponent, PropType } from 'vue'
import { RouteLocationRaw } from 'vue-router'
export default defineComponent({
props: {
name: {
type: String,
required: true
},
index: {
type: String,
required: true
},
active: {
type: Boolean,
required: false,
default: false
},
target: {
type: [String, Object] as PropType<RouteLocationRaw>,
required: false,
default: null
},
icon: {
type: String,
required: true
},
fillType: {
type: String,
required: false,
default: 'fill'
},
collapsed: {
type: Boolean,
required: false,
default: false
},
handler: {
type: Function as PropType<() => void>,
required: false,
default: null
}
},
setup(props) {
const attrs = computed(() => {
return {
...(props.handler && { onClick: props.handler }),
...(props.target && { to: props.target })
}
})
return { attrs }
},
computed: {
navName() {
if (this.target) {
return this.$router?.resolve(this.target, this.$route)?.name || 'route.name'
}
return this.name
},
toolTip() {
const value = this.collapsed
? this.$gettext('Navigate to %{ pageName } page', {
pageName: this.name
})
: ''
return {
content: value,
placement: 'right',
arrow: false
}
}
}
})
</script>
<style lang="scss">
.oc-sidebar-nav-item-link {
position: relative;
align-items: center !important;
display: flex !important;
justify-content: space-between !important;
padding: var(--oc-space-small) !important;
border-radius: 5px;
white-space: nowrap;
user-select: none;
.oc-tag {
color: var(--oc-color-text-default);
background-color: var(--oc-color-background-highlight);
}
.text {
opacity: 1;
transition: all 0.3s;
}
.text-invisible {
opacity: 0 !important;
transition: 0s;
}
&:hover:not(.active) {
color: var(--oc-color-swatch-brand-hover) !important;
}
&:hover,
&:focus {
text-decoration: none !important;
}
&.active {
overflow: hidden;
}
.oc-icon svg {
transition: all 0.3s;
}
}
</style>
| owncloud/web/packages/web-runtime/src/components/SidebarNav/SidebarNavItem.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/components/SidebarNav/SidebarNavItem.vue",
"repo_id": "owncloud",
"token_count": 1351
} | 867 |
import { useTask } from 'vue-concurrency'
import convert from 'xml-js'
import { useClientService, useAuthStore, AuthStore } from '@ownclouders/web-pkg'
import { ClientService } from '@ownclouders/web-pkg'
import { urlJoin } from '@ownclouders/web-client/src/utils'
export interface LoadTokenInfoOptions {
clientService?: ClientService
authStore?: AuthStore
}
export function useLoadTokenInfo(options: LoadTokenInfoOptions) {
const clientService = options.clientService || useClientService()
const authStore = options.authStore || useAuthStore()
const loadTokenInfoTask = useTask(function* (signal, token: string) {
try {
const url = authStore.userContextReady
? 'ocs/v1.php/apps/files_sharing/api/v1/tokeninfo/protected'
: 'ocs/v1.php/apps/files_sharing/api/v1/tokeninfo/unprotected'
// FIXME: use graph endpoint as soon as it's available: https://github.com/owncloud/ocis/issues/8617
const { data } = authStore.userContextReady
? yield clientService.httpAuthenticated.get(urlJoin(url, token))
: yield clientService.httpUnAuthenticated.get(urlJoin(url, token))
const parsedData = convert.xml2js(data, { compact: true, nativeType: false }) as any
const tokenInfo = parsedData.ocs.data
return {
id: tokenInfo.id._text,
link_url: tokenInfo.link_url._text,
alias_link: tokenInfo.alias_link._text === 'true',
password_protected: tokenInfo.password_protected._text === 'true',
token
}
} catch (e) {
// backend doesn't support the token info endpoint
return {}
}
})
return { loadTokenInfoTask }
}
| owncloud/web/packages/web-runtime/src/composables/tokenInfo/useLoadTokenInfo.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/composables/tokenInfo/useLoadTokenInfo.ts",
"repo_id": "owncloud",
"token_count": 585
} | 868 |
import { AppNavigationItem, ExtensionRegistry, SidebarNavExtension } from '@ownclouders/web-pkg'
export interface NavItem extends Omit<AppNavigationItem, 'name'> {
name: string
active: boolean
}
export const getExtensionNavItems = ({
extensionRegistry,
appId
}: {
extensionRegistry: ExtensionRegistry
appId: string
}) =>
extensionRegistry
.requestExtensions<SidebarNavExtension>('sidebarNav', [`app.${appId}`])
.map(({ navItem }) => navItem)
.filter((n) => !Object.hasOwn(n, 'isVisible') || n.isVisible())
| owncloud/web/packages/web-runtime/src/helpers/navItems.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/helpers/navItems.ts",
"repo_id": "owncloud",
"token_count": 182
} | 869 |
<template>
<div
class="oc-link-resolve oc-height-viewport oc-flex oc-flex-column oc-flex-center oc-flex-middle"
>
<div class="oc-card oc-text-center oc-width-large">
<template v-if="loading">
<div class="oc-card-header">
<h2 key="private-link-loading" class="oc-link-resolve-loading">
<span v-text="$gettext('Resolving private link…')" />
</h2>
</div>
<div class="oc-card-body">
<oc-spinner :aria-hidden="true" />
</div>
</template>
<template v-else-if="errorMessage">
<div class="oc-card-header oc-link-resolve-error-title">
<h2 key="private-link-error">
<span v-text="$gettext('An error occurred while resolving the private link')" />
</h2>
</div>
<div class="oc-card-body oc-link-resolve-error-message">
<p class="oc-text-xlarge">{{ errorMessage }}</p>
<p
v-if="isUnacceptedShareError"
v-text="$gettext('You can reload this page after you have enabled syncing the share.')"
/>
</div>
</template>
</div>
<oc-button
v-if="isUnacceptedShareError"
type="router-link"
variation="primary"
appearance="filled"
target="_blank"
class="oc-mt-m oc-text-center oc-width-medium"
:to="sharedWithMeRoute"
>
<span class="text" v-text="openSharedWithMeLabel" />
</oc-button>
</div>
</template>
<script lang="ts">
import {
useRouteParam,
useRouter,
queryItemAsString,
useRouteQuery,
createLocationSpaces,
createLocationShares,
useConfigStore,
useClientService
} from '@ownclouders/web-pkg'
import { unref, defineComponent, computed, onMounted, ref, Ref } from 'vue'
// import { createLocationSpaces } from 'web-app-files/src/router'
import { dirname } from 'path'
import { createFileRouteOptions, useGetResourceContext } from '@ownclouders/web-pkg'
import { useTask } from 'vue-concurrency'
import { isShareSpaceResource, Resource, SHARE_JAIL_ID } from '@ownclouders/web-client/src/helpers'
import { RouteLocationNamedRaw } from 'vue-router'
import { useGettext } from 'vue3-gettext'
import { DriveItem } from '@ownclouders/web-client/src/generated'
export default defineComponent({
name: 'ResolvePrivateLink',
setup() {
const router = useRouter()
const id = useRouteParam('fileId')
const configStore = useConfigStore()
const { $gettext } = useGettext()
const clientService = useClientService()
const resource: Ref<Resource> = ref()
const sharedParentResource: Ref<Resource> = ref()
const isUnacceptedShareError = ref(false)
const { getResourceContext } = useGetResourceContext()
const openWithDefaultAppQuery = useRouteQuery('openWithDefaultApp')
const openWithDefaultApp = computed(() => queryItemAsString(unref(openWithDefaultAppQuery)))
const detailsQuery = useRouteQuery('details')
const details = computed(() => {
return queryItemAsString(unref(detailsQuery))
})
onMounted(() => {
resolvePrivateLinkTask.perform(queryItemAsString(unref(id)))
})
const resolvePrivateLinkTask = useTask(function* (signal, id) {
if (
[
`${SHARE_JAIL_ID}$${SHARE_JAIL_ID}!${SHARE_JAIL_ID}`,
`${SHARE_JAIL_ID}$${SHARE_JAIL_ID}`
].includes(id)
) {
return router.push(createLocationShares('files-shares-with-me'))
}
let result: Awaited<ReturnType<typeof getResourceContext>>
try {
result = yield getResourceContext(id)
} catch (e) {
// error means the resurce is an unaccepted/unsynced share
isUnacceptedShareError.value = true
throw Error(e)
}
const { space, resource } = result
let { path } = result
if (!path) {
// empty path means the user has no access to the resource or it doesn't exist
throw new Error('The file or folder does not exist')
}
let resourceIsNestedInShare = false
let isHiddenShare = false
if (isShareSpaceResource(space)) {
sharedParentResource.value = resource
resourceIsNestedInShare = path !== '/'
if (!resourceIsNestedInShare && space.shareId) {
// FIXME: get drive item by id as soon as server supports it
const { data } = yield clientService.graphAuthenticated.drives.listSharedWithMe()
const share = (data.value as DriveItem[]).find(
({ remoteItem }) => remoteItem.id === resource.id
)
isHiddenShare = share?.['@UI.Hidden']
}
}
let fileId: string
let targetLocation: RouteLocationNamedRaw
if (unref(resource).type === 'folder') {
fileId = unref(resource).fileId
targetLocation = createLocationSpaces('files-spaces-generic')
} else {
fileId = unref(resource).parentFolderId
path = dirname(path)
targetLocation =
space.driveType === 'share' && !resourceIsNestedInShare
? createLocationShares('files-shares-with-me')
: createLocationSpaces('files-spaces-generic')
}
const { params, query } = createFileRouteOptions(space, { fileId, path })
const openWithDefault =
configStore.options.openLinksWithDefaultApp &&
unref(openWithDefaultApp) !== 'false' &&
!unref(details)
targetLocation.params = params
targetLocation.query = {
...query,
scrollTo:
targetLocation.name === 'files-shares-with-me' ? space.shareId : unref(resource).fileId,
...(unref(details) && { details: unref(details) }),
...(isHiddenShare && { 'q_share-visibility': 'hidden' }),
...(openWithDefault && { openWithDefaultApp: 'true' })
}
router.push(targetLocation)
})
const loading = computed(() => {
return !resolvePrivateLinkTask.last || resolvePrivateLinkTask.isRunning
})
const sharedWithMeRoute = computed(() => {
return { name: 'files-shares-with-me' }
})
const openSharedWithMeLabel = computed(() => {
return $gettext('Open "Shared with me"')
})
const errorMessage = computed(() => {
if (unref(isUnacceptedShareError)) {
if (!unref(sharedParentResource)) {
return $gettext(
'This file or folder has been shared with you. Enable the sync in "Shares" > "Shared with me" to view it.'
)
} else {
return $gettext(
'This file or folder has been shared with you via "%{parentShareName}". Enable the sync for the share "%{parentShareName}" in "Shares" > "Shared with me" to view it.',
{
parentShareName: unref(sharedParentResource).name
}
)
}
}
if (resolvePrivateLinkTask.isError) {
return resolvePrivateLinkTask.last.error.message
}
return null
})
return {
errorMessage,
loading,
resource,
isUnacceptedShareError,
sharedWithMeRoute,
openSharedWithMeLabel,
// HACK: for unit tests
resolvePrivateLinkTask
}
}
})
</script>
<style lang="scss">
.oc-link-resolve {
.oc-card {
background: var(--oc-color-background-highlight);
border-radius: 15px;
}
.oc-card-header h2 {
margin: 0;
}
}
</style>
| owncloud/web/packages/web-runtime/src/pages/resolvePrivateLink.vue/0 | {
"file_path": "owncloud/web/packages/web-runtime/src/pages/resolvePrivateLink.vue",
"repo_id": "owncloud",
"token_count": 3024
} | 870 |
import { useMessages } from '@ownclouders/web-pkg'
import { OcNotificationMessage } from 'design-system/src/components'
import MessageBar from 'web-runtime/src/components/MessageBar.vue'
import { defaultPlugins, shallowMount } from 'web-test-helpers'
const messages = [
{
id: '101',
title: 'Error while moving',
desc: '',
status: 'danger'
},
{
id: '102',
title: 'Error while deleting',
desc: '',
status: 'danger'
},
{
id: '103',
title: 'Error while renaming',
desc: '',
status: 'danger'
},
{
id: '104',
title: 'Error while copying',
desc: '',
status: 'danger'
},
{
id: '105',
title: 'Error while restoring',
desc: '',
status: 'danger'
},
{
id: '106',
title: 'Error while uploading',
desc: '',
status: 'danger'
}
]
const selectors = {
notificationMessage: 'oc-notification-message-stub'
}
describe('MessageBar component', () => {
describe('when there is an active message', () => {
it('should set props in oc-notification-message component', () => {
const { wrapper } = getShallowWrapper([messages[0]])
const notificationMessage = wrapper.findComponent<typeof OcNotificationMessage>(
selectors.notificationMessage
)
expect(notificationMessage.attributes().title).toEqual(messages[0].title)
expect(notificationMessage.attributes().status).toEqual(messages[0].status)
expect(notificationMessage.attributes().message).toEqual(messages[0].desc)
})
it('should call "removeMessage" method on close event', () => {
const { wrapper } = getShallowWrapper([messages[0]])
const messageStore = useMessages()
const notificationMessage = wrapper.findComponent<typeof OcNotificationMessage>(
selectors.notificationMessage
)
notificationMessage.vm.$emit('close')
expect(messageStore.removeMessage).toHaveBeenCalledTimes(1)
})
})
describe('when there are more than five active messages', () => {
it('should return only the first five messages', () => {
const { wrapper } = getShallowWrapper(messages)
expect(wrapper.findAll(selectors.notificationMessage).length).toBe(5)
})
})
})
function getShallowWrapper(messages = []) {
return {
wrapper: shallowMount(MessageBar, {
global: {
renderStubDefaultSlot: true,
plugins: [...defaultPlugins({ piniaOptions: { messagesState: { messages } } })]
}
})
}
}
| owncloud/web/packages/web-runtime/tests/unit/components/MessageBar.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/MessageBar.spec.ts",
"repo_id": "owncloud",
"token_count": 917
} | 871 |
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`ApplicationsMenu component > should render navigation with button and menu items in dropdown 1`] = `
"<nav data-v-33cec29f="" id="applications-menu" aria-label="Main navigation" class="oc-flex oc-flex-middle">
<oc-button-stub data-v-33cec29f="" type="button" disabled="false" size="medium" arialabel="Application Switcher" submit="button" variation="brand" appearance="raw-inverse" justifycontent="center" gapsize="medium" showspinner="false" id="_appSwitcherButton" class="oc-topbar-menu-burger">
<oc-icon-stub data-v-33cec29f="" name="grid" filltype="fill" accessiblelabel="" type="span" size="large" variation="passive" color="" class="oc-flex"></oc-icon-stub>
</oc-button-stub>
<oc-drop-stub data-v-33cec29f="" dropid="app-switcher-dropdown" popperoptions="[object Object]" toggle="#_appSwitcherButton" position="bottom-start" mode="click" closeonclick="true" isnested="false" paddingsize="small">
<div data-v-33cec29f="" class="oc-display-block oc-position-relative">
<oc-list-stub data-v-33cec29f="" raw="false" class="applications-list">
<li data-v-33cec29f="">
<oc-button-stub data-v-33cec29f="" type="router-link" disabled="false" size="medium" to="/files" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false" class="">
<oc-application-icon-stub data-v-33cec29f="" icon="folder" colorprimary="" colorsecondary=""></oc-application-icon-stub> <span data-v-33cec29f="">Files</span>
</oc-button-stub>
</li>
<li data-v-33cec29f="">
<oc-button-stub data-v-33cec29f="" type="a" disabled="false" size="medium" href="http://some.org" target="_blank" submit="button" variation="passive" appearance="raw" justifycontent="center" gapsize="medium" showspinner="false" class="">
<oc-application-icon-stub data-v-33cec29f="" icon="some-icon" colorprimary="" colorsecondary=""></oc-application-icon-stub> <span data-v-33cec29f="">External</span>
</oc-button-stub>
</li>
</oc-list-stub>
</div>
</oc-drop-stub>
</nav>"
`;
| owncloud/web/packages/web-runtime/tests/unit/components/Topbar/__snapshots__/ApplicationsMenu.spec.ts.snap/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/components/Topbar/__snapshots__/ApplicationsMenu.spec.ts.snap",
"repo_id": "owncloud",
"token_count": 828
} | 872 |
import resolvePrivateLink from '../../../src/pages/resolvePrivateLink.vue'
import {
defaultPlugins,
defaultComponentMocks,
shallowMount,
mockAxiosResolve
} from 'web-test-helpers'
import { mock } from 'vitest-mock-extended'
import { queryItemAsString, useGetResourceContext } from '@ownclouders/web-pkg'
import { Resource, SpaceResource } from '@ownclouders/web-client'
import { SHARE_JAIL_ID } from '@ownclouders/web-client/src/helpers'
import { DriveItem } from '@ownclouders/web-client/src/generated'
vi.mock('@ownclouders/web-pkg', async (importOriginal) => ({
...(await importOriginal<any>()),
useRouteQuery: vi.fn((str) => str),
useRouteParam: vi.fn((str) => str),
queryItemAsString: vi.fn(),
useGetResourceContext: vi.fn()
}))
const selectors = {
loadingHeadline: '.oc-link-resolve-loading'
}
describe('resolvePrivateLink', () => {
it('is in a loading state initially', () => {
const { wrapper } = getWrapper()
expect(wrapper.find(selectors.loadingHeadline).exists()).toBeTruthy()
})
it('resolves to "files-spaces-generic" and passes the scrollTo query', async () => {
const fileId = '1'
const driveAliasAndItem = 'personal/home'
const space = mock<SpaceResource>({ getDriveAliasAndItem: () => driveAliasAndItem })
const resource = mock<Resource>({ fileId })
const { wrapper, mocks } = getWrapper({ space, resource, fileId, path: '/' })
await wrapper.vm.resolvePrivateLinkTask.last
expect(mocks.$router.push).toHaveBeenCalledWith(
expect.objectContaining({
name: 'files-spaces-generic',
params: expect.objectContaining({ driveAliasAndItem }),
query: expect.objectContaining({ scrollTo: fileId })
})
)
})
describe('resolves to "files-shares-with-me"', () => {
it('resolves for single file shares', async () => {
const fileId = '1'
const driveAliasAndItem = 'shares/someShare'
const space = mock<SpaceResource>({
driveType: 'share',
getDriveAliasAndItem: () => driveAliasAndItem
})
const resource = mock<Resource>({ fileId, type: 'file' })
const { wrapper, mocks } = getWrapper({ space, resource, fileId, path: '/' })
await wrapper.vm.resolvePrivateLinkTask.last
expect(mocks.$router.push).toHaveBeenCalledWith(
expect.objectContaining({ name: 'files-shares-with-me' })
)
})
it.each([
`${SHARE_JAIL_ID}$${SHARE_JAIL_ID}`,
`${SHARE_JAIL_ID}$${SHARE_JAIL_ID}!${SHARE_JAIL_ID}`
])('resolves for the share jail id', async (fileId) => {
const { wrapper, mocks } = getWrapper({ fileId })
await wrapper.vm.resolvePrivateLinkTask.last
expect(mocks.$router.push).toHaveBeenCalledWith(
expect.objectContaining({ name: 'files-shares-with-me' })
)
})
it('adds the hidden share param for hidden shares', async () => {
const fileId = '1'
const driveAliasAndItem = 'shares/someShare'
const space = mock<SpaceResource>({
driveType: 'share',
getDriveAliasAndItem: () => driveAliasAndItem
})
const resource = mock<Resource>({ fileId, id: fileId, type: 'file' })
const { wrapper, mocks } = getWrapper({
space,
resource,
fileId,
path: '/',
hiddenShare: true
})
await wrapper.vm.resolvePrivateLinkTask.last
expect(mocks.$router.push).toHaveBeenCalledWith(
expect.objectContaining({
query: expect.objectContaining({ 'q_share-visibility': 'hidden' })
})
)
})
})
it('passes the details query param if given via query', async () => {
const details = 'sharing'
const { wrapper, mocks } = getWrapper({ details, path: '/' })
await wrapper.vm.resolvePrivateLinkTask.last
expect(mocks.$router.push).toHaveBeenCalledWith(
expect.objectContaining({ query: expect.objectContaining({ details }) })
)
})
it('throws an error if the path is empty', async () => {
const { wrapper } = getWrapper()
try {
await wrapper.vm.resolvePrivateLinkTask.last
} catch (e) {}
expect(wrapper.find('.oc-link-resolve-error-message p').text()).toEqual(
'The file or folder does not exist'
)
})
describe('openWithDefaultApp', () => {
it('correctly passes the openWithDefaultApp param if enabled and given via query', async () => {
const { wrapper, mocks } = getWrapper({ path: '/' })
await wrapper.vm.resolvePrivateLinkTask.last
expect(mocks.$router.push).toHaveBeenCalledWith(
expect.objectContaining({ query: expect.objectContaining({ openWithDefaultApp: 'true' }) })
)
})
it('does not pass the openWithDefaultApp param when details param is given', async () => {
const { wrapper, mocks } = getWrapper({ details: 'sharing', path: '/' })
await wrapper.vm.resolvePrivateLinkTask.last
expect(mocks.$router.push).toHaveBeenCalledWith(
expect.objectContaining({
query: expect.not.objectContaining({ openWithDefaultApp: 'true' })
})
)
})
it('does not pass the openWithDefaultApp param when disabled via config', async () => {
const { wrapper, mocks } = getWrapper({ openLinksWithDefaultApp: false, path: '/' })
await wrapper.vm.resolvePrivateLinkTask.last
expect(mocks.$router.push).toHaveBeenCalledWith(
expect.objectContaining({
query: expect.not.objectContaining({ openWithDefaultApp: 'true' })
})
)
})
it('does not pass the openWithDefaultApp param when not requested via query', async () => {
const { wrapper, mocks } = getWrapper({ openWithDefaultAppQuery: 'false', path: '/' })
await wrapper.vm.resolvePrivateLinkTask.last
expect(mocks.$router.push).toHaveBeenCalledWith(
expect.objectContaining({
query: expect.not.objectContaining({ openWithDefaultApp: 'true' })
})
)
})
})
})
function getWrapper({
space = mock<SpaceResource>(),
resource = mock<Resource>(),
path = '',
fileId = '',
details = '',
hiddenShare = false,
openWithDefaultAppQuery = 'true',
openLinksWithDefaultApp = true
} = {}) {
vi.mocked(queryItemAsString).mockImplementation((str: string) => {
if (str === 'fileId') {
return fileId
}
if (str === 'openWithDefaultApp') {
return openWithDefaultAppQuery
}
if (str === 'details') {
return details
}
return str
})
vi.mocked(useGetResourceContext).mockReturnValue({
getResourceContext: vi.fn().mockResolvedValue({ space, resource, path })
})
const mocks = { ...defaultComponentMocks() }
mocks.$clientService.graphAuthenticated.drives.listSharedWithMe.mockResolvedValue(
mockAxiosResolve({
value: [{ remoteItem: { id: '1' }, '@UI.Hidden': hiddenShare } as DriveItem]
})
)
return {
mocks,
wrapper: shallowMount(resolvePrivateLink, {
global: {
plugins: [
...defaultPlugins({
piniaOptions: { configState: { options: { openLinksWithDefaultApp } } }
})
],
mocks,
provide: mocks
}
})
}
}
| owncloud/web/packages/web-runtime/tests/unit/pages/resolvePrivateLink.spec.ts/0 | {
"file_path": "owncloud/web/packages/web-runtime/tests/unit/pages/resolvePrivateLink.spec.ts",
"repo_id": "owncloud",
"token_count": 2736
} | 873 |
import { mock, mockDeep } from 'vitest-mock-extended'
import {
ClientService,
LoadingService,
LoadingTaskCallbackArguments,
PasswordPolicyService,
PreviewService,
UppyService
} from '../../../web-pkg/src/'
import { Router, RouteLocationNormalizedLoaded, RouteLocationRaw } from 'vue-router'
import { ref } from 'vue'
export interface ComponentMocksOptions {
currentRoute?: RouteLocationNormalizedLoaded
}
export const defaultComponentMocks = ({ currentRoute = undefined }: ComponentMocksOptions = {}) => {
const $router = mockDeep<Router>({ ...(currentRoute && { currentRoute: ref(currentRoute) }) })
$router.resolve.mockImplementation(
(to: RouteLocationRaw) => ({ href: (to as any).name, location: { path: '' } }) as any
)
const $route = $router.currentRoute.value
$route.path = $route.path || '/'
return {
$router,
$route,
$clientService: mockDeep<ClientService>(),
$previewService: mockDeep<PreviewService>(),
$uppyService: mockDeep<UppyService>(),
$loadingService: mock<LoadingService>({
addTask: (callback) => {
return callback(mock<LoadingTaskCallbackArguments>())
}
}),
$passwordPolicyService: mockDeep<PasswordPolicyService>()
}
}
| owncloud/web/packages/web-test-helpers/src/mocks/defaultComponentMocks.ts/0 | {
"file_path": "owncloud/web/packages/web-test-helpers/src/mocks/defaultComponentMocks.ts",
"repo_id": "owncloud",
"token_count": 410
} | 874 |
// from https://github.com/nightwatchjs/nightwatch/issues/1132#issuecomment-340257894
// and adjusted a bit
// because calling "clearValue()" does not trigger Vue events when using v-model
/**
* A better `clearValue` for inputs having a more complex interaction.
*
* @export
* @param {string} selector
* @returns
*/
exports.command = function clearValueWithEvent(selector) {
const { END, BACK_SPACE } = this.Keys
return this.getValue(selector, (result) => {
const chars = result.value.split('')
// Make sure we are at the end of the input
this.setValue(selector, END)
// Delete all the existing characters
chars.forEach(() => this.setValue(selector, BACK_SPACE))
})
}
| owncloud/web/tests/acceptance/customCommands/clearValueWithEvent.js/0 | {
"file_path": "owncloud/web/tests/acceptance/customCommands/clearValueWithEvent.js",
"repo_id": "owncloud",
"token_count": 223
} | 875 |
Feature: create folder
As a user
I want to create folders
So that I can organise my data structure
Background:
Given user "Alice" has been created with default attributes and without skeleton files in the server
And user "Alice" has logged in using the webUI
And the user has reloaded the current page of the webUI
Scenario Outline: Create a folder using special characters
When the user creates a folder with the name <folder_name> using the webUI
Then folder <folder_name> should be listed on the webUI
When the user reloads the current page of the webUI
Then folder <folder_name> should be listed on the webUI
Examples:
| folder_name |
| '"somequotes1"' |
| "'somequotes2'" |
| "\"quote\"d-folders'" |
| "^#29][29@({" |
| "+-{$(882)" |
| "home" |
| "Sample,Folder,With,Comma" |
| 'सिमप्ले फोल्देर $%#?&@' |
@issue-2467 @ocis-reva-issue-106
Scenario Outline: Create a sub-folder inside a folder with problematic name
# First try and create a folder with problematic name
# Then try and create a sub-folder inside the folder with problematic name
When the user creates a folder with the name <folder> using the webUI
And the user opens folder <folder> using the webUI
Then there should be no resources listed on the webUI
When the user creates a folder with the name "sub-folder" using the webUI
Then folder "sub-folder" should be listed on the webUI
When the user reloads the current page of the webUI
Then folder "sub-folder" should be listed on the webUI
And as "Alice" folder "sub-folder" should exist inside folder <folder> in the server
Examples:
| folder |
#| "?&%0" |
| "^#2929@" |
| "home" |
@smokeTest @ocis-reva-issue-106
Scenario Outline: Create a sub-folder inside an existing folder with problematic name
# Use an existing folder with problematic name to create a sub-folder
# Uses the folder created by skeleton
Given user "Alice" has created folder <folder> in the server
And the user has reloaded the current page of the webUI
When the user opens folder <folder> using the webUI
And the user creates a folder with the name "sub-folder" using the webUI
Then folder "sub-folder" should be listed on the webUI
When the user reloads the current page of the webUI
Then folder "sub-folder" should be listed on the webUI
And as "Alice" folder "sub-folder" should exist inside folder <folder> in the server
Examples:
| folder |
| "0" |
| "'single'quotes" |
| "strängé नेपाली folder" |
| owncloud/web/tests/acceptance/features/webUICreateFilesFolders/createFolderEdgeCases.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUICreateFilesFolders/createFolderEdgeCases.feature",
"repo_id": "owncloud",
"token_count": 1040
} | 876 |
Feature: Sharing files and folders with internal users
As a user
I want to share files and folders with other users
So that those users can access the files and folders
Background:
Given the administrator has set the default folder for received shares to "Shares" in the server
And these users have been created with default attributes and without skeleton files in the server:
| username |
| Alice |
| Brian |
And user "Brian" has created folder "simple-folder" in the server
@issue-2897 @issue-ocis-2260 @disablePreviews
Scenario: sharing details of items inside a shared folder ("via" info)
Given user "Alice" has created folder "simple-folder" in the server
And user "Alice" has created folder "simple-folder/simple-empty-folder" in the server
And user "Carol" has been created with default attributes and without skeleton files in the server
And user "Alice" has uploaded file with content "test" to "/simple-folder/lorem.txt" in the server
And user "Alice" has shared folder "simple-folder" with user "Brian" in the server
And user "Alice" has logged in using the webUI
And the user opens folder "simple-folder" using the webUI
When the user opens the details dialog for folder "simple-empty-folder" using the webUI
Then the shared-via path in the details dialog should be "/simple-folder"
When the user opens the details dialog for file "lorem.txt" using the webUI
Then the shared-via path in the details dialog should be "/simple-folder"
| owncloud/web/tests/acceptance/features/webUISharingInternalUsers/shareWithUsers.feature/0 | {
"file_path": "owncloud/web/tests/acceptance/features/webUISharingInternalUsers/shareWithUsers.feature",
"repo_id": "owncloud",
"token_count": 424
} | 877 |
const { client } = require('nightwatch-api')
function cleanupLogMessage(message) {
return message.replace(/\\u003C/gi, '').replace(/\\n/g, '\n') // revive newlines
}
function formatLog(log) {
return (
new Date(log.timestamp).toLocaleTimeString() +
' - ' +
log.level +
' - ' +
cleanupLogMessage(log.message)
)
}
async function getAllLogs() {
let logs = []
await client.getLog('browser', (entries) => {
logs = entries
})
return logs
}
exports.getAllLogsWithDateTime = async function (level = null) {
let logs = await getAllLogs()
if (level) {
logs = logs.filter((entry) => entry.level === level)
}
return logs.filter((e) => !e.message.includes('favicon.ico')).map(formatLog)
}
| owncloud/web/tests/acceptance/helpers/browserConsole.js/0 | {
"file_path": "owncloud/web/tests/acceptance/helpers/browserConsole.js",
"repo_id": "owncloud",
"token_count": 272
} | 878 |
const util = require('util')
const timeoutHelper = require('../../../helpers/timeoutHelper')
const { client } = require('nightwatch-api')
module.exports = {
commands: {
/**
* @param {string} collaborator
* @returns {Promise.<string[]>} Array of autocomplete webElementIds
*/
deleteShareWithUserGroup: function (collaborator) {
this.expandShareEditDropdown(collaborator)
const deleteSelector = this.elements.deleteShareButton.selector
const dialogSelector = this.elements.dialog.selector
const dialogConfirmSelector = this.elements.dialogConfirmBtn.selector
return this.useXpath()
.waitForElementVisible(deleteSelector)
.waitForAnimationToFinish() // wait for animation of share sliding out
.click(deleteSelector)
.waitForElementVisible(dialogSelector)
.waitForAnimationToFinish() // wait for transition on the modal to finish
.click(dialogConfirmSelector)
.waitForAjaxCallsToStartAndFinish()
.waitForElementNotPresent('@collaboratorEditDropDownList')
},
/**
* Open the role selection dialog for a new share or for editing the given collaborator
*
* @param {string | null} collaborator
*/
expandShareRoleDropdown: function (collaborator = null) {
if (!collaborator) {
return this.waitForElementVisible('@newShareRoleButton').click('@newShareRoleButton')
}
const informationSelector = util.format(
this.elements.collaboratorInformationByCollaboratorName.selector,
collaborator
)
const editRoleSelector = informationSelector + this.elements.editShareRoleButton.selector
return this.useXpath().waitForElementVisible(editRoleSelector).click(editRoleSelector)
},
expandShareEditDropdown: function (collaborator) {
const informationSelector = util.format(
this.elements.collaboratorInformationByCollaboratorName.selector,
collaborator
)
const editDropdownSelector = informationSelector + this.elements.editDropdown.selector
return this.useXpath().waitForElementVisible(editDropdownSelector).click(editDropdownSelector)
},
expandExpirationDatePicker: function (collaborator) {
if (!collaborator) {
this.waitForElementVisible('@threeDotsTrigger').click('@threeDotsTrigger')
this.waitForElementVisible('@setExpirationDateButton').click('@setExpirationDateButton')
return client.page.FilesPageElement.expirationDatePicker()
}
const informationSelector = util.format(
this.elements.collaboratorInformationByCollaboratorName.selector,
collaborator
)
const editExpirationSelector =
informationSelector + this.elements.expirationDatePickerTrigger.selector
this.useXpath().waitForElementVisible(editExpirationSelector).click(editExpirationSelector)
return client.page.FilesPageElement.expirationDatePicker()
},
hasCollaboratorsList: async function (expectCollaborator = true) {
let isVisible = false
const element = this.elements.collaboratorsList
const timeout = expectCollaborator
? this.api.globals.waitForConditionTimeout
: this.api.globals.waitForNegativeConditionTimeout
await this.isVisible(
{
locateStrategy: element.locateStrategy,
selector: element.selector,
timeout: timeoutHelper.parseTimeout(timeout),
suppressNotFoundErrors: !expectCollaborator
},
(result) => {
isVisible = result.value === true
}
)
return isVisible
},
/**
*
* @param {Object.<String,Object>} subSelectors Map of arbitrary attribute name to selector to query
* inside the collaborator element, defaults to all when null
* @param filterDisplayName Instead of reading the full list of sharees, only grab the one sharee that matches the given display name
* @param timeout
* @returns {Promise.<string[]>} Array of users/groups in share list
*/
getCollaboratorsList: async function (
subSelectors = null,
filterDisplayName = null,
timeout = null
) {
const results = []
let listItemSelector = {
selector: this.elements.collaboratorsListItem.selector
}
timeout = timeoutHelper.parseTimeout(timeout)
if (filterDisplayName !== null) {
listItemSelector = {
selector: util.format(
this.elements.collaboratorInformationByCollaboratorName.selector,
filterDisplayName
),
locateStrategy: this.elements.collaboratorInformationByCollaboratorName.locateStrategy,
timeout
}
}
if (subSelectors === null) {
subSelectors = {
displayName: this.elements.collaboratorInformationSubName,
role: this.elements.collaboratorInformationSubRole,
additionalInfo: this.elements.collaboratorInformationSubAdditionalInfo,
shareType: this.elements.collaboratorShareType
}
}
let listItemElementIds = []
await this.waitForElementPresent('@collaboratorsList').api.elements(
'css selector',
listItemSelector,
(result) => {
if (result.status === -1) {
return
}
listItemElementIds = listItemElementIds.concat(
result.value.map((item) => item[Object.keys(item)[0]])
)
}
)
for (const collaboratorElementId of listItemElementIds) {
const collaboratorResult = {}
let collaboratorEditButton = null
await this.api.elementIdElement(
collaboratorElementId,
'css selector',
this.elements.collaboratorEditButton,
(result) => {
collaboratorEditButton = result.value.ELEMENT
}
)
await this.api.elementIdClick(collaboratorEditButton)
let accessDetailsBtn = null
await this.api.elementIdElement(
collaboratorElementId,
'css selector',
this.elements.collaboratorAccessDetailsButton,
(result) => {
accessDetailsBtn = result.value.ELEMENT
}
)
await this.api.elementIdClick(accessDetailsBtn)
this.waitForElementVisible(this.elements.collaboratorAccessDetailsDrop)
for (const attrName in subSelectors) {
let attrElementId = null
await this.api.elementIdElement(
collaboratorElementId,
'css selector',
subSelectors[attrName],
(result) => {
if (result.status !== -1) {
attrElementId = result.value.ELEMENT
}
}
)
if (attrElementId) {
await this.api.elementIdText(attrElementId, (text) => {
collaboratorResult[attrName] = text.value
})
} else {
collaboratorResult[attrName] = false
}
}
results.push(collaboratorResult)
let collaboratorAvatarElId = null
await this.api.elementIdElement(
collaboratorElementId,
'css selector',
'.files-collaborators-collaborator-indicator',
(result) => {
collaboratorAvatarElId = result.value.ELEMENT
}
)
// to hide the access details dialog from the screen, click on the collaborator avatar
await this.api.elementIdClick(collaboratorAvatarElId)
await this.waitForElementNotPresent(
'@collaboratorAccessDetailsDrop',
this.api.globals.waitForConditionTimeout
)
}
return results
},
/**
*
* @returns {Promise.<string[]>} Array of user/group display names in share list
*/
getCollaboratorsListNames: async function () {
const list = await this.getCollaboratorsList({
name: this.elements.collaboratorInformationSubName
})
return list.map((result) => result.name)
},
/**
* check if the expiration date is present in the collaborator share and then get the expiration information
* @return {Promise.<string>}
*/
getCollaboratorExpirationInfo: async function (user) {
let text
const formattedWithUserName = util.format(
this.elements.collaboratorExpirationInfo.selector,
user
)
const formattedCollaboratorInfoByCollaboratorName = util.format(
this.elements.collaboratorInformationByCollaboratorName.selector,
user
)
await this.useXpath()
.waitForElementVisible(formattedCollaboratorInfoByCollaboratorName)
.getText('xpath', formattedWithUserName, function (result) {
if (typeof result.value === 'string') {
text = result.value
}
})
return text
}
},
elements: {
collaboratorInformationByCollaboratorName: {
selector:
'//span[contains(@class, "files-collaborators-collaborator-name") and contains(text(),"%s")]/ancestor::li',
locateStrategy: 'xpath'
},
deleteShareButton: {
// within collaboratorInformationByCollaboratorName
selector: '//button[contains(@class, "remove-share")]',
locateStrategy: 'xpath'
},
dialog: {
selector: '//div[contains(@class, "oc-modal")]',
locateStrategy: 'xpath'
},
dialogConfirmBtn: {
selector: '//button[contains(@class, "oc-modal-body-actions-confirm")]',
locateStrategy: 'xpath'
},
createShareDialog: {
selector: '#new-collaborators-form'
},
newShareRoleButton: {
selector: '#files-collaborators-role-button-new'
},
editShareRoleButton: {
// within collaboratorInformationByCollaboratorName
selector: '//button[contains(@class, "files-recipient-role-select-btn")]',
locateStrategy: 'xpath'
},
editDropdown: {
// within collaboratorInformationByCollaboratorName
selector: '//button[contains(@class, "collaborator-edit-dropdown-options-btn")]',
locateStrategy: 'xpath'
},
editShareDialog: {
selector: '//*[contains(@class, "files-collaborators-collaborator-edit-dialog")]',
locateStrategy: 'xpath'
},
collaboratorsList: {
// container around collaborator list items
selector: '#files-collaborators-list',
locateStrategy: 'css selector'
},
collaboratorsListItem: {
// addresses users and groups
selector: '.files-collaborators-collaborator'
},
collaboratorInformationSubName: {
// within collaboratorsListItem
selector: '.files-collaborators-collaborator-name'
},
collaboratorInformationSubRole: {
// within collaboratorsListItem
selector: '.files-recipient-role-select-btn:first-child'
},
collaboratorInformationSubAdditionalInfo: {
// within collaboratorsListItem
selector:
'//div[contains(@class, "share-access-details-drop")]//dt[contains(text(),"Additional info")]/following-sibling::dd[1]',
locateStrategy: 'xpath'
},
collaboratorShareType: {
selector:
'//div[contains(@class, "share-access-details-drop")]//dt[contains(text(),"Type")]/following-sibling::dd[1]',
locateStrategy: 'xpath'
},
collaboratorExpirationInfo: {
selector:
'//p[contains(@class, "files-collaborators-collaborator-name") and text()="%s"]/../..//span[contains(@class, "files-collaborators-collaborator-expires")]',
locateStrategy: 'xpath'
},
threeDotsTrigger: {
selector: 'button#show-more-share-options-btn'
},
setExpirationDateButton: {
selector: '.files-recipient-expiration-datepicker'
},
expirationDatePickerTrigger: {
selector: '//button[contains(@class, "files-collaborators-expiration-button")]',
locateStrategy: 'xpath'
},
collaboratorEditButton: {
selector: '.collaborator-edit-dropdown-options-btn'
},
collaboratorAccessDetailsButton: {
selector: '.show-access-details'
},
collaboratorAccessDetailsDrop: {
selector: '.share-access-details-drop'
},
collaboratorEditDropDownList: {
selector: '.collaborator-edit-dropdown-options-list'
}
}
}
| owncloud/web/tests/acceptance/pageObjects/FilesPageElement/SharingDialog/collaboratorsDialog.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/FilesPageElement/SharingDialog/collaboratorsDialog.js",
"repo_id": "owncloud",
"token_count": 4917
} | 879 |
const { join } = require('../helpers/path')
module.exports = {
url: function () {
return join(this.api.launchUrl, '/access-denied')
},
elements: {
body: 'body',
loginErrorMessage: {
locateStrategy: 'xpath',
selector: '//h2[text()="Not logged in"]'
},
exitButton: {
selector: '#exitAnchor'
}
},
commands: {
waitTillLoaded: function () {
const element = this.elements.loginErrorMessage
return this.useStrategy(element).waitForElementVisible(element)
},
exit: function () {
const exitBtn = this.elements.exitButton
return this.waitForElementVisible(exitBtn).click(exitBtn)
}
}
}
| owncloud/web/tests/acceptance/pageObjects/loginErrorPage.js/0 | {
"file_path": "owncloud/web/tests/acceptance/pageObjects/loginErrorPage.js",
"repo_id": "owncloud",
"token_count": 271
} | 880 |
const { setDefaultTimeout, After, Before, defineParameterType } = require('@cucumber/cucumber')
const {
createSession,
closeSession,
client,
startWebDriver,
stopWebDriver
} = require('nightwatch-api')
const fs = require('fs')
const { rollbackConfigs, cacheConfigs } = require('./helpers/config')
const { getAllLogsWithDateTime } = require('./helpers/browserConsole.js')
const { runOcc } = require('./helpers/occHelper')
const codify = require('./helpers/codify')
const RUNNING_ON_CI = process.env.CI === 'true'
const CUCUMBER_LOCAL_TIMEOUT = 60000
const CUCUMBER_DRONE_TIMEOUT = 180000
const CUCUMBER_TIMEOUT = RUNNING_ON_CI ? CUCUMBER_DRONE_TIMEOUT : CUCUMBER_LOCAL_TIMEOUT
setDefaultTimeout(CUCUMBER_TIMEOUT)
const env = RUNNING_ON_CI ? 'drone' : 'local'
// create report dir if not exists
const reportDir = 'report'
if (!fs.existsSync(reportDir)) {
fs.mkdirSync(reportDir)
}
defineParameterType({
name: 'code',
regexp: /"([^"\\]*(\\.[^"\\]*)*)"|'([^'\\]*(\\.[^'\\]*)*)'/,
type: String,
transformer: (s) => codify.replaceInlineCode(s)
})
Before(function startDriverOnLocal() {
return RUNNING_ON_CI || startWebDriver({ env })
})
Before(function createSessionForEnv() {
return createSession({ env })
})
async function cacheAndSetConfigs(server) {
if (client.globals.ocis) {
return
}
await cacheConfigs(server)
}
Before(function cacheAndSetConfigsOnLocal() {
if (client.globals.ocis) {
return
}
return cacheAndSetConfigs(client.globals.backend_url)
})
Before(function cacheAndSetConfigsOnRemoteIfExists() {
if (client.globals.ocis) {
return
}
if (client.globals.remote_backend_url) {
return cacheAndSetConfigs(client.globals.remote_backend_url)
}
})
// Delete share_folder config
// Some tests will fail if this config was already set in the system
Before(function deleteShareFolderConfig() {
if (client.globals.ocis) {
return
}
return runOcc(['config:system:delete share_folder'])
})
// After hooks are run in reverse order in which they are defined
// https://github.com/cucumber/cucumber-js/blob/master/docs/support_files/hooks.md#hooks
After(function rollbackConfigsOnRemoteIfExists() {
if (client.globals.ocis) {
return
}
if (client.globals.remote_backend_url) {
return rollbackConfigs(client.globals.remote_backend_url)
}
})
After(function rollbackConfigsOnLocal() {
if (client.globals.ocis) {
return
}
return rollbackConfigs(client.globals.backend_url)
})
After(function stopDriverIfOnLocal() {
return RUNNING_ON_CI || stopWebDriver()
})
After(function closeSessionForEnv() {
return closeSession()
})
After(async function tryToReadBrowserConsoleOnFailure({ result }) {
if (result.status === 'failed') {
const logs = await getAllLogsWithDateTime('SEVERE')
if (logs.length > 0) {
console.log('\nThe following logs were found in the browser console:\n')
logs.forEach((log) => console.log(log))
}
}
// The tests give following warning
// MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 unhandledRejection listeners added
// this clears all remaining eventListeners before proceeding to next test
process.removeAllListeners()
})
| owncloud/web/tests/acceptance/setup.js/0 | {
"file_path": "owncloud/web/tests/acceptance/setup.js",
"repo_id": "owncloud",
"token_count": 1128
} | 881 |
Feature: spaces management
Scenario: spaces can be managed in the admin settings via the context menu
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
| Brian | Space Admin |
When "Alice" logs in
And "Alice" creates the following project spaces using API
| name | id |
| team A | team.a |
| team B | team.b |
When "Alice" opens the "admin-settings" app
And "Alice" navigates to the project spaces management page
When "Alice" updates the space "team.a" name to "developer team" using the context-menu
And "Alice" updates the space "team.a" subtitle to "developer team-subtitle" using the context-menu
And "Alice" updates the space "team.a" quota to "50" using the context-menu
And "Alice" disables the space "team.a" using the context-menu
And "Alice" enables the space "team.a" using the context-menu
Then "Alice" should see the following spaces
| id |
| team.a |
And "Alice" logs out
When "Brian" logs in
And "Brian" opens the "admin-settings" app
And "Brian" navigates to the project spaces management page
When "Brian" disables the space "team.b" using the context-menu
And "Brian" deletes the space "team.b" using the context-menu
Then "Brian" should not see the following spaces
| id |
| team.b |
And "Brian" logs out
Scenario: multiple spaces can be managed at once in the admin settings via the batch actions
Given "Admin" creates following user using API
| id |
| Alice |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
And "Alice" logs in
And "Alice" creates the following project spaces using API
| name | id |
| team A | team.a |
| team B | team.b |
| team C | team.c |
| team D | team.d |
When "Alice" opens the "admin-settings" app
And "Alice" navigates to the project spaces management page
And "Alice" disables the following spaces using the batch-actions
| id |
| team.a |
| team.b |
| team.c |
| team.d |
And "Alice" enables the following spaces using the batch-actions
| id |
| team.a |
| team.b |
| team.c |
| team.d |
And "Alice" updates quota of the following spaces to "50" using the batch-actions
| id |
| team.a |
| team.b |
| team.c |
| team.d |
And "Alice" disables the following spaces using the batch-actions
| id |
| team.a |
| team.b |
| team.c |
| team.d |
And "Alice" deletes the following spaces using the batch-actions
| id |
| team.a |
| team.b |
| team.c |
| team.d |
Then "Alice" should not see the following spaces
| id |
| team.a |
| team.b |
| team.c |
| team.d |
And "Alice" logs out
Scenario: list members via sidebar
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
| Carol |
| David |
| Edith |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
And "Admin" creates the following project spaces using API
| name | id |
| team A | team.a |
And "Admin" adds the following members to the space "team A" using API
| user | role | shareType |
| Brian | Can edit | space |
| Carol | Can view | space |
| David | Can view | space |
| Edith | Can view | space |
When "Alice" logs in
And "Alice" opens the "admin-settings" app
And "Alice" navigates to the project spaces management page
When "Alice" lists the members of project space "team.a" using a sidebar panel
Then "Alice" should see the following users in the sidebar panel of spaces admin settings
| user | role |
| Admin | Can manage |
| Brian | Can edit |
| Carol | Can view |
| David | Can view |
| Edith | Can view |
And "Alice" logs out
Scenario: admin user can manage the spaces created by other space admin user
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
| Carol |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Admin |
| Brian | Space Admin |
| Carol | Space Admin |
When "Brian" logs in
And "Brian" creates the following project spaces using API
| name | id |
| team A | team.a |
And "Brian" logs out
When "Carol" logs in
And "Carol" creates the following project spaces using API
| name | id |
| team B | team.b |
And "Carol" logs out
When "Alice" logs in
And "Alice" opens the "admin-settings" app
And "Alice" navigates to the project spaces management page
And "Alice" updates quota of the following spaces to "50" using the batch-actions
| id |
| team.a |
| team.b |
And "Alice" disables the following spaces using the batch-actions
| id |
| team.a |
| team.b |
And "Alice" enables the following spaces using the batch-actions
| id |
| team.a |
| team.b |
And "Alice" disables the following spaces using the batch-actions
| id |
| team.a |
| team.b |
And "Alice" deletes the following spaces using the batch-actions
| id |
| team.a |
| team.b |
Then "Alice" should not see the following spaces
| id |
| team.a |
| team.b |
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/admin-settings/spaces.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/admin-settings/spaces.feature",
"repo_id": "owncloud",
"token_count": 2355
} | 882 |
Feature: create Space shortcut
Scenario: create Space from folder
Given "Admin" creates following users using API
| id |
| Alice |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
And "Alice" logs in
And "Alice" creates the following folder in personal space using API
| name |
| spaceFolder |
| spaceFolder/test |
And "Alice" navigates to the personal space page
And "Alice" uploads the following resources
| resource | to |
| data.zip | spaceFolder |
| lorem.txt | spaceFolder |
And "Alice" navigates to the personal space page
And "Alice" creates space "folderSpace" from folder "spaceFolder" using the context menu
And "Alice" navigates to the projects space page
And "Alice" navigates to the project space "folderSpace"
Then following resources should be displayed in the files list for user "Alice"
| resource |
| data.zip |
| lorem.txt |
And "Alice" logs out
Scenario: create space from resources
Given "Admin" creates following users using API
| id |
| Alice |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
And "Alice" logs in
And "Alice" creates the following folder in personal space using API
| name |
| resourceFolder |
And "Alice" navigates to the personal space page
And "Alice" uploads the following resources
| resource | to |
| data.zip | resourceFolder |
| lorem.txt | |
And "Alice" navigates to the personal space page
And "Alice" creates space "resourceSpace" from resources using the context menu
| resource |
| resourceFolder |
| lorem.txt |
And "Alice" navigates to the projects space page
And "Alice" navigates to the project space "resourceSpace"
Then following resources should be displayed in the files list for user "Alice"
| resource |
| resourceFolder |
| lorem.txt |
And "Alice" logs out
| owncloud/web/tests/e2e/cucumber/features/smoke/createSpaceFromSelection.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/smoke/createSpaceFromSelection.feature",
"repo_id": "owncloud",
"token_count": 896
} | 883 |
Feature: internal link share in project space
Scenario: share a link with internal role
Given "Admin" creates following users using API
| id |
| Alice |
| Brian |
| Carol |
And "Admin" assigns following roles to the users using API
| id | role |
| Alice | Space Admin |
And "Alice" logs in
And "Alice" creates the following project space using API
| name | id |
| Marketing | marketing.1 |
And "Alice" creates the following folder in space "Marketing" using API
| name |
| myfolder |
And "Alice" creates the following file in space "Marketing" using API
| name | content |
| myfolder/plan.txt | secret plan |
And "Alice" adds the following members to the space "Marketing" using API
| user | role | shareType |
| Brian | Can edit | space |
| Carol | Can view | space |
And "Alice" navigates to the projects space page
And "Alice" navigates to the project space "marketing.1"
# internal link to space
And "Alice" creates a public link for the space with password "%public%" using the sidebar panel
And "Alice" renames the most recently created public link of space to "spaceLink"
And "Alice" edits the public link named "spaceLink" of the space changing role to "Invited people"
# internal link to folder
And "Alice" creates a public link creates a public link of following resource using the sidebar panel
| resource | role | password |
| myfolder | Invited people | %public% |
# When "Alice" edits the public link named "Link" of resource "myfolder" changing role to "Invited people"
And "Alice" logs out
And "Brian" opens the public link "Link"
And "Brian" logs in from the internal link
And "Brian" uploads the following resource in internal link named "Link"
| resource |
| simple.pdf |
And "Brian" logs out
When "Carol" opens the public link "spaceLink"
And "Carol" logs in from the internal link
And "Carol" opens folder "myfolder"
Then "Carol" should see file "simple.pdf" but should not be able to edit
And "Carol" logs out
| owncloud/web/tests/e2e/cucumber/features/spaces/internalLink.feature/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/features/spaces/internalLink.feature",
"repo_id": "owncloud",
"token_count": 764
} | 884 |
import { DataTable, When, Then } from '@cucumber/cucumber'
import path from 'path'
import { World } from '../../environment'
import { objects } from '../../../support'
import { expect } from '@playwright/test'
import { config } from '../../../config'
import {
createResourceTypes,
displayedResourceType,
shortcutType,
ActionViaType
} from '../../../support/objects/app-files/resource/actions'
import { Public } from '../../../support/objects/app-files/page/public'
import { Resource } from '../../../support/objects/app-files'
import * as runtimeFs from '../../../support/utils/runtimeFs'
import { searchFilter } from '../../../support/objects/app-files/resource/actions'
import { File } from '../../../support/types'
When(
'{string} creates the following resource(s)',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const info of stepTable.hashes()) {
await resourceObject.create({
name: info.resource,
type: info.type as createResourceTypes,
content: info.content
})
}
}
)
When(
'{string} uploads the following resource(s)',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const info of stepTable.hashes()) {
await resourceObject.upload({
to: info.to,
resources: [this.filesEnvironment.getFile({ name: info.resource })],
option: info.option
})
}
}
)
When(
'{string} tries to upload the following resource',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const info of stepTable.hashes()) {
await resourceObject.tryToUpload({
to: info.to,
resources: [this.filesEnvironment.getFile({ name: info.resource })],
error: info.error
})
}
}
)
When(
'{string} starts uploading the following large resource(s) from the temp upload directory',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const info of stepTable.hashes()) {
await resourceObject.startUpload({
to: info.to,
resources: [
this.filesEnvironment.getFile({
name: path.join(runtimeFs.getTempUploadPath().replace(config.assets, ''), info.resource)
})
],
option: info.option
})
}
}
)
When(
'{string} {word} the file upload',
async function (this: World, stepUser: string, action: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
switch (action) {
case 'pauses':
await resourceObject.pauseUpload()
break
case 'resumes':
await resourceObject.resumeUpload()
break
case 'cancels':
await resourceObject.cancelUpload()
break
default:
throw new Error(`Unknown action: ${action}`)
}
}
)
When(
/^"([^"]*)" downloads the following resource(?:s)? using the (sidebar panel|batch action)$/,
async function (this: World, stepUser: string, actionType: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await processDownload(stepTable, resourceObject, actionType)
}
)
When(
/^"([^"]*)" downloads the following image(?:s)? from the mediaviewer$/,
async function (this: World, stepUser: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await processDownload(stepTable, resourceObject, 'preview')
}
)
When(
/^"([^"]*)" deletes the following resource(?:s)? using the (sidebar panel|batch action)$/,
async function (this: World, stepUser: string, actionType: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await processDelete(stepTable, resourceObject, actionType)
}
)
When(
'{string} renames the following resource(s)',
async function (this: World, stepUser: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const { resource, as } of stepTable.hashes()) {
await resourceObject.rename({ resource, newName: as })
}
}
)
When(
/^"([^"]*)" (copies|moves) the following resource(?:s)? using (keyboard|drag-drop|drag-drop-breadcrumb|sidebar-panel|dropdown-menu|batch-action)$/,
async function (
this: World,
stepUser: string,
actionType: string,
method: string,
stepTable: DataTable
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const { resource, to, option } of stepTable.hashes()) {
await resourceObject[actionType === 'copies' ? 'copy' : 'move']({
resource,
newLocation: to,
method,
option: option
})
}
}
)
When(
/^"([^"]*)" (copies|moves) the following resources to "([^"]*)" at once using (keyboard|drag-drop|drag-drop-breadcrumb|dropdown-menu|batch-action)$/,
async function (
this: World,
stepUser: string,
actionType: string,
newLocation: string,
method: string,
stepTable: DataTable
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
const resources = [].concat(...stepTable.rows())
await resourceObject[
actionType === 'copies' ? 'copyMultipleResources' : 'moveMultipleResources'
]({
newLocation,
method,
resources
})
}
)
When(
'{string} restores following resource(s)',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
const fileInfo = stepTable.hashes().reduce((acc, stepRow) => {
const { to, resource, version, openDetailsPanel } = stepRow
if (!acc[to]) {
acc[to] = []
}
acc[to].push(this.filesEnvironment.getFile({ name: resource }))
if (version !== '1') {
throw new Error('restoring is only supported for the most recent version')
}
acc[to]['openDetailsPanel'] = openDetailsPanel === 'true'
return acc
}, [])
for (const folder of Object.keys(fileInfo)) {
await resourceObject.restoreVersion({
folder,
files: fileInfo[folder],
openDetailsPanel: fileInfo[folder]['openDetailsPanel']
})
}
}
)
When(
'{string} downloads old version of the following resource(s)',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
const fileInfo = stepTable.hashes().reduce((acc, stepRow) => {
const { to, resource } = stepRow
if (!acc[to]) {
acc[to] = []
}
acc[to].push(this.filesEnvironment.getFile({ name: resource }))
return acc
}, [])
for (const folder of Object.keys(fileInfo)) {
await resourceObject.downloadVersion({ folder, files: fileInfo[folder] })
}
}
)
When(
'{string} deletes the following resources from trashbin using the batch action',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
const resources = [].concat(...stepTable.rows())
await resourceObject.deleteTrashbinMultipleResources({ resources })
}
)
When(
'{string} empties the trashbin',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.emptyTrashbin({ page })
}
)
Then(
/^"([^"]*)" (should|should not) be able to delete following resource(?:s)? from the trashbin?$/,
async function (
this: World,
stepUser: string,
actionType: string,
stepTable: DataTable
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const info of stepTable.hashes()) {
if (actionType === 'should') {
const message = await resourceObject.deleteTrashBin({ resource: info.resource })
const paths = info.resource.split('/')
expect(message).toBe(`"${paths[paths.length - 1]}" was deleted successfully`)
} else {
await resourceObject.expectThatDeleteTrashBinButtonIsNotVisible({ resource: info.resource })
}
}
}
)
Then(
/^"([^"]*)" (should|should not) be able to restore following resource(?:s)? from the trashbin?$/,
async function (
this: World,
stepUser: string,
actionType: string,
stepTable: DataTable
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const info of stepTable.hashes()) {
if (actionType === 'should') {
const message = await resourceObject.restoreTrashBin({
resource: info.resource
})
const paths = info.resource.split('/')
expect(message).toBe(`${paths[paths.length - 1]} was restored successfully`)
} else {
await resourceObject.expectThatRestoreTrashBinButtonIsNotVisible({
resource: info.resource
})
}
}
}
)
Then(
'{string} restores the following resource from trashbin',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const info of stepTable.hashes()) {
const message = await resourceObject.restoreTrashBin({ resource: info.resource })
const paths = info.resource.split('/')
expect(message).toBe(`${paths[paths.length - 1]} was restored successfully`)
}
}
)
When(
/^"([^"]*)" searches "([^"]*)" using the global search(?: and the "([^"]*)" filter)?( and presses enter)?$/,
async function (
this: World,
stepUser: string,
keyword: string,
filter: string,
command: string
): Promise<void> {
keyword = keyword ?? ''
const pressEnter = !!command && command.endsWith('presses enter')
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.searchResource({
keyword,
filter: filter as searchFilter,
pressEnter
})
}
)
Then(
/^following resources (should|should not) be displayed in the (search list|files list|Shares|trashbin) for user "([^"]*)"$/,
async function (
this: World,
actionType: string,
listType: string,
stepUser: string,
stepTable: DataTable
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
const actualList = await resourceObject.getDisplayedResources({
keyword: listType as displayedResourceType
})
for (const info of stepTable.hashes()) {
expect(actualList.includes(info.resource)).toBe(actionType === 'should')
}
}
)
When(
'{string} opens folder {string}',
async function (this: World, stepUser: string, resource: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.openFolder(resource)
}
)
When(
'{string} navigates to folder {string} via breadcrumb',
async function (this: World, stepUser: string, resource: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.openFolderViaBreadcrumb(resource)
}
)
When(
'{string} enables the option to display the hidden file',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.showHiddenFiles()
}
)
When(
'{string} switches to the tiles-view',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.switchToTilesViewMode()
}
)
When(
'{string} sees the resources displayed as tiles',
async function (this: World, stepUser: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.expectThatResourcesAreTiles()
}
)
export const processDelete = async (
stepTable: DataTable,
pageObject: Public | Resource,
actionType: string
) => {
let files, parentFolder
const deleteInfo = stepTable.hashes().reduce((acc, stepRow) => {
const { resource, from } = stepRow
const resourceInfo = {
name: resource
}
if (!acc[from]) {
acc[from] = []
}
acc[from].push(resourceInfo)
return acc
}, [])
for (const folder of Object.keys(deleteInfo)) {
files = deleteInfo[folder]
parentFolder = folder !== 'undefined' ? folder : null
await pageObject.delete({
folder: parentFolder,
resourcesWithInfo: files,
via: actionType === 'batch action' ? 'BATCH_ACTION' : 'SIDEBAR_PANEL'
})
}
}
export const processDownload = async (
stepTable: DataTable,
pageObject: Public | Resource,
actionType: string
) => {
let downloads, files, parentFolder
const downloadedResources = []
const downloadInfo = stepTable.hashes().reduce((acc, stepRow) => {
const { resource, from, type } = stepRow
const resourceInfo = {
name: resource,
type: type
}
if (!acc[from]) {
acc[from] = []
}
acc[from].push(resourceInfo)
return acc
}, [])
for (const folder of Object.keys(downloadInfo)) {
files = downloadInfo[folder]
parentFolder = folder !== 'undefined' ? folder : null
let via: ActionViaType = 'SINGLE_SHARE_VIEW'
switch (actionType) {
case 'batch action':
via = 'BATCH_ACTION'
break
case 'sidebar panel':
via = 'SIDEBAR_PANEL'
break
case 'preview':
via = 'PREVIEW'
break
default:
break
}
downloads = await pageObject.download({
folder: parentFolder,
resources: files,
via
})
downloads.forEach((download) => {
const { name } = path.parse(download.suggestedFilename())
downloadedResources.push(name)
})
if (actionType === 'sidebar panel') {
expect(downloads.length).toBe(files.length)
for (const resource of files) {
const fileOrFolderName = path.parse(resource.name).name
if (resource.type === 'file') {
expect(downloadedResources).toContain(fileOrFolderName)
} else {
expect(downloadedResources).toContain('download')
}
}
}
}
if (actionType === 'batch action') {
expect(downloads.length).toBe(1)
downloads.forEach((download) => {
const { name } = path.parse(download.suggestedFilename())
expect(name).toBe('download')
})
}
}
When(
'{string} edits the following resource(s)',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const info of stepTable.hashes()) {
await resourceObject.editResource({ name: info.resource, content: info.content })
}
}
)
When(
'{string} clicks the tag {string} on the resource {string}',
async function (
this: World,
stepUser: string,
tagName: string,
resourceName: string
): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.clickTag({ resource: resourceName, tag: tagName.toLowerCase() })
}
)
When(
/^"([^"].*)" opens the following file(?:s)? in (mediaviewer|pdfviewer|texteditor|Collabora|OnlyOffice)$/,
async function (this: World, stepUser: string, actionType: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const info of stepTable.hashes()) {
await resourceObject.openFileInViewer({
name: info.resource,
actionType: actionType as
| 'mediaviewer'
| 'pdfviewer'
| 'texteditor'
| 'Collabora'
| 'OnlyOffice'
})
}
}
)
Then(
'the following resource(s) should contain the following tag(s) in the files list for user {string}',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const { resource, tags } of stepTable.hashes()) {
const isVisible = await resourceObject.areTagsVisibleForResourceInFilesTable({
resource,
tags: tags.split(',').map((tag) => tag.trim().toLowerCase())
})
expect(isVisible).toBe(true)
}
}
)
Then(
'the following resource(s) should contain the following tag(s) in the details panel for user {string}',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const { resource, tags } of stepTable.hashes()) {
const isVisible = await resourceObject.areTagsVisibleForResourceInDetailsPanel({
resource,
tags: tags.split(',').map((tag) => tag.trim().toLowerCase())
})
expect(isVisible).toBe(true)
}
}
)
When(
'{string} adds the following tag(s) for the following resource(s) using the sidebar panel',
async function (this: World, stepUser: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const { resource, tags } of stepTable.hashes()) {
await resourceObject.addTags({
resource,
tags: tags.split(',').map((tag) => tag.trim().toLowerCase())
})
}
}
)
When(
'{string} removes the following tag(s) for the following resource(s) using the sidebar panel',
async function (this: World, stepUser: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const { resource, tags } of stepTable.hashes()) {
await resourceObject.removeTags({
resource,
tags: tags.split(',').map((tag) => tag.trim().toLowerCase())
})
}
}
)
When(
'{string} creates space {string} from folder {string} using the context menu',
async function (this: World, stepUser: string, spaceName: string, folderName: string) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
const space = await resourceObject.createSpaceFromFolder({
folderName: folderName,
spaceName: spaceName
})
this.spacesEnvironment.createSpace({
key: space.name,
space: { name: space.name, id: space.id }
})
}
)
When(
'{string} creates space {string} from resources using the context menu',
async function (this: World, stepUser: string, spaceName: string, stepTable: DataTable) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
const resources = stepTable.hashes().map((item) => item.resource)
const space = await resourceObject.createSpaceFromSelection({ resources, spaceName })
this.spacesEnvironment.createSpace({
key: space.name,
space: { name: space.name, id: space.id }
})
}
)
Then(
'{string} should not see the version of the file(s)',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
const fileInfo = stepTable.hashes().reduce<File[]>((acc, stepRow) => {
const { to, resource } = stepRow
if (!acc[to]) {
acc[to] = []
}
acc[to].push(this.filesEnvironment.getFile({ name: resource }))
return acc
}, [])
for (const folder of Object.keys(fileInfo)) {
await resourceObject.checkThatFileVersionIsNotAvailable({ folder, files: fileInfo[folder] })
}
}
)
When(
'{string} navigates to page {string} of the personal/project space files view',
async function (this: World, stepUser: string, pageNumber: string) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.changePage({ pageNumber })
}
)
When(
'{string} changes the items per page to {string}',
async function (this: World, stepUser: string, itemsPerPage: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.changeItemsPerPage({ itemsPerPage })
}
)
Then(
'{string} should see the text {string} at the footer of the page',
async function (this: World, stepUser: string, expectedText: string) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
const actualText = await resourceObject.getFileListFooterText()
expect(actualText).toBe(expectedText)
}
)
Then(
'{string} should see {int} resources in the personal/project space files view',
async function (this: World, stepUser: string, expectedNumberOfResources: number) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
const actualNumberOfResources = await resourceObject.countNumberOfResourcesInThePage()
expect(actualNumberOfResources).toBe(expectedNumberOfResources)
}
)
Then(
'{string} should not see the pagination in the personal/project space files view',
async function (this: World, stepUser: string) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.expectPageNumberNotToBeVisible()
}
)
When(
'{string} uploads the following resource(s) via drag-n-drop',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
const resources = stepTable
.hashes()
.map((item) => this.filesEnvironment.getFile({ name: item.resource }))
await resourceObject.dropUpload({ resources })
}
)
When(
'{string} uploads {int} small files in personal space',
async function (this: World, stepUser: string, numberOfFiles: number): Promise<void> {
const files = []
for (let i = 0; i < numberOfFiles; i++) {
const file = `file${i}.txt`
runtimeFs.createFile(file, 'test content')
files.push(
this.filesEnvironment.getFile({
name: path.join(runtimeFs.getTempUploadPath().replace(config.assets, ''), file)
})
)
}
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.uploadLargeNumberOfResources({ resources: files })
}
)
When(
'{string} creates a shortcut for the following resource(s)',
async function (this: World, stepUser: string, stepTable: DataTable): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
for (const info of stepTable.hashes()) {
await resourceObject.createShotcut({
resource: info.resource,
name: info.name,
type: info.type as shortcutType
})
}
}
)
When(
'{string} opens a shortcut {string}',
async function (this: World, stepUser: string, name: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.openShotcut({ name: name })
}
)
Then(
'{string} can open a shortcut {string} with external url {string}',
async function (this: World, stepUser: string, name: string, url: string): Promise<void> {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
await resourceObject.openShotcut({ name: name, url: url })
}
)
Then(
/^for "([^"]*)" file "([^"]*)" (should|should not) be locked$/,
async function (this: World, stepUser: string, file: string, actionType: string) {
const { page } = this.actorsEnvironment.getActor({ key: stepUser })
const resourceObject = new objects.applicationFiles.Resource({ page })
const lockLocator = resourceObject.getLockLocator({ resource: file })
actionType === 'should'
? await expect(lockLocator).toBeVisible()
: await expect(lockLocator).not.toBeVisible()
}
)
| owncloud/web/tests/e2e/cucumber/steps/ui/resources.ts/0 | {
"file_path": "owncloud/web/tests/e2e/cucumber/steps/ui/resources.ts",
"repo_id": "owncloud",
"token_count": 9401
} | 885 |
export {
me,
createUser,
deleteUser,
createGroup,
deleteGroup,
addUserToGroup,
assignRole,
getUserId
} from './userManagement'
export {
getPersonalSpaceId,
createSpace,
getSpaceIdBySpaceName,
disableSpace,
deleteSpace
} from './spaces'
| owncloud/web/tests/e2e/support/api/graph/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/api/graph/index.ts",
"repo_id": "owncloud",
"token_count": 93
} | 886 |
import { kebabCase } from 'lodash'
import { DateTime } from 'luxon'
import { Actor } from '../../types'
import { ActorsOptions } from './shared'
import { ActorEnvironment } from './actor'
import { actorStore } from '../../store'
import EventEmitter from 'events'
export class ActorsEnvironment extends EventEmitter {
private readonly options: ActorsOptions
constructor(options: ActorsOptions) {
super()
this.options = options
}
public getActor({ key }: { key: string }): Actor {
if (!actorStore.has(key)) {
throw new Error(`actor with key '${key}' not found`)
}
return actorStore.get(key)
}
public async createActor({ key, namespace }: { key: string; namespace: string }): Promise<Actor> {
if (actorStore.has(key)) {
return this.getActor({ key })
}
const actor = new ActorEnvironment({ id: key, namespace, ...this.options })
await actor.setup()
actor.on('closed', () => actorStore.delete(key))
actor.page.on('console', (message) => {
this.emit('console', key, message)
})
actorStore.set(key, actor)
return actor
}
public async close(): Promise<void> {
await Promise.all([...actorStore.values()].map((actor) => actor.close()))
}
public generateNamespace(scenarioTitle: string, user: string): string {
return kebabCase([scenarioTitle, user, DateTime.now().toFormat('yyyy-M-d-hh-mm-ss')].join('-'))
}
}
| owncloud/web/tests/e2e/support/environment/actor/actors.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/environment/actor/actors.ts",
"repo_id": "owncloud",
"token_count": 482
} | 887 |
export * as page from './page'
export { Spaces } from './spaces'
export { Users } from './users'
export { General } from './general'
export { Groups } from './groups'
| owncloud/web/tests/e2e/support/objects/app-admin-settings/index.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-admin-settings/index.ts",
"repo_id": "owncloud",
"token_count": 51
} | 888 |
import { Page } from '@playwright/test'
const sharesNavSelector = '//a[@data-nav-name="files-shares"]'
export class WithOthers {
#page: Page
constructor({ page }: { page: Page }) {
this.#page = page
}
async navigate(): Promise<void> {
await this.#page.locator(sharesNavSelector).click()
await this.#page.getByText('Shared with others').click()
}
}
| owncloud/web/tests/e2e/support/objects/app-files/page/shares/withOthers.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/page/shares/withOthers.ts",
"repo_id": "owncloud",
"token_count": 131
} | 889 |
import { Page } from '@playwright/test'
import util from 'util'
const spaceIdSelector = '//tr[@data-item-id="%s"]//a'
export interface openTrashBinArgs {
id: string
page: Page
}
export const openTrashbin = async (args: openTrashBinArgs): Promise<void> => {
const { id, page } = args
await page.locator(util.format(spaceIdSelector, id)).click()
}
| owncloud/web/tests/e2e/support/objects/app-files/trashbin/actions.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/objects/app-files/trashbin/actions.ts",
"repo_id": "owncloud",
"token_count": 125
} | 890 |
export const userRoleStore = new Map<string, string>()
| owncloud/web/tests/e2e/support/store/role.ts/0 | {
"file_path": "owncloud/web/tests/e2e/support/store/role.ts",
"repo_id": "owncloud",
"token_count": 15
} | 891 |
{
"extends": "@ownclouders/tsconfig"
}
| owncloud/web/tsconfig.json/0 | {
"file_path": "owncloud/web/tsconfig.json",
"repo_id": "owncloud",
"token_count": 18
} | 892 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
include_once "inc/config.inc.php";
$dbhost=DBHOST;
$dbuser=DBUSER;
$dbpw=DBPW;
$dbname=DBNAME;
$mes_connect='';
$mes1='';
$mes2='';
$mes_ok='';
if(isset($_POST['submit'])) {
//判断数据库连接
if (!@mysqli_connect($dbhost, $dbuser, $dbpw)) {
exit('数据连接失败,请仔细检查inc/config.inc.php的配置');
}
$link = mysqli_connect(DBHOST, DBUSER, DBPW);
$mes_connect .= "<p class='notice'>数据库连接成功!</p>";
//如果存在,则直接干掉
$drop_db = "drop database if exists $dbname";
if (!@mysqli_query($link, $drop_db)) {
exit('初始化数据库失败,请仔细检查当前用户是否有操作权限');
}
//创建数据库
$create_db = "CREATE DATABASE $dbname";
if (!@mysqli_query($link, $create_db)) {
exit('数据库创建失败,请仔细检查当前用户是否有操作权限');
}
$mes_create = "<p class='notice'>新建数据库:" . $dbname . "成功!</p>";
//创建数据.选择数据库
if (!@mysqli_select_db($link, $dbname)) {
exit('数据库选择失败,请仔细检查当前用户是否有操作权限');
}
//创建users表
$creat_users =
"CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL,
`password` varchar(66) NOT NULL,
`level` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4";
if (!@mysqli_query($link, $creat_users)) {
exit('创建users表失败,请仔细检查当前用户是否有操作权限');
}
//往users表里面插入默认的数据
$insert_users = "insert into `users` (`id`,`username`,`password`,`level`) values (1,'admin',md5('123456'),1)";
if (!@mysqli_query($link, $insert_users)) {
echo $link->error;
exit('创建users表数据失败,请仔细检查当前用户是否有操作权限');
}
$mes1 = "<p class='notice'>新建数据库表users成功!</p>";
//创建cookie结果表
//time,ipaddress,cookie,referer,useragent
$creat_cookieresult = "CREATE TABLE IF NOT EXISTS `cookies` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT,`time` TIMESTAMP,`ipaddress` VARCHAR(50),`cookie` VARCHAR(1000),`referer` VARCHAR(1000),`useragent` VARCHAR(1000),PRIMARY KEY (`id`))";
if (!@mysqli_query($link, $creat_cookieresult)) {
exit('创建cookie表失败,请仔细检查当前用户是否有操作权限');
}
//创建xfish结果表
$creat_xfish = "CREATE TABLE IF NOT EXISTS `fish` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT,`time` TIMESTAMP,`username` VARCHAR(50),`password` VARCHAR(50),`referer` VARCHAR(1000),PRIMARY KEY (`id`))";
if (!@mysqli_query($link, $creat_xfish)) {
exit('创建fish表失败,请仔细检查当前用户是否有操作权限');
}
//创建键盘记录表
$creat_keypress = "CREATE TABLE IF NOT EXISTS `keypress` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT,`data` VARCHAR(1000),PRIMARY KEY (`id`))";
if (!@mysqli_query($link, $creat_keypress)) {
exit('创建keypress表失败,请仔细检查当前用户是否有操作权限');
}
$mes2 = "<p class='notice'>新建数据库表cookie,fish成功!</p>";
$mes_ok="<p class='notice'>好了,可以了<a href='pkxss_login.php'>点击这里</a>进入首页</p>";
}
?>
<html>
<body>
<div class="page-content">
<div id=install_main>
<p class="main_title">Setup guide:</p>
<p class="main_title">第0步:请提前安装“mysql+php+中间件”的环境;</p>
<p class="main_title">第1步:请根据实际环境修改pkxss/inc/config.inc.php文件里面的参数;</p>
<p class="main_title">第2步:点击“安装/初始化”按钮;</p>
<form method="post">
<input type="submit" name="submit" value="安装/初始化"/>
</form>
</div>
<div class="info" style="color: #D6487E;padding-top: 40px;">
<?php
echo $mes_connect;
echo $mes1;
echo $mes2;
echo $mes_ok;
?>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
</body>
</html>
| zhuifengshaonianhanlu/pikachu/pkxss/pkxss_install.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/pkxss/pkxss_install.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2334
} | 893 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR.'inc/config.inc.php';
include_once $PIKA_ROOT_DIR.'inc/mysql.inc.php';
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "bf_client.php"){
$ACTIVE = array('','active open','','','','active',"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","");
}
include_once $PIKA_ROOT_DIR.'header.php';
$link=connect();
$html="";
if(isset($_POST['submit'])){
if($_POST['username'] && $_POST['password']) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "select * from users where username=? and password=md5(?)";
$line_pre = $link->prepare($sql);
$line_pre->bind_param('ss', $username, $password);
if ($line_pre->execute()) {
$line_pre->store_result();
if ($line_pre->num_rows > 0) {
$html .= '<p> login success</p>';
} else {
$html .= '<p> username or password is not exists~</p>';
}
} else {
$html .= '<p>执行错误:' . $line_pre->errno . '错误信息:' . $line_pre->error . '</p>';
}
}else{
$html .= '<p> please input username and password~</p>';
}
}
?>
<div class="main-content" xmlns="http://www.w3.org/1999/html">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="burteforce.php">暴力破解</a>
</li>
<li class="active">验证码绕过(on client)</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="仔细看下,这个验证码到底是个什么鬼?..看看前端JS源码,发现什么了吗?">
点一下提示~
</a>
</div>
<div class="page-content">
<div class="bf_form">
<div class="bf_form_main">
<h4 class="header blue lighter bigger">
<i class="ace-icon fa fa-coffee green"></i>
Please Enter Your Information
</h4>
<form id="bf_client" method="post" action="bf_client.php" onsubmit="return validate();">
<!-- <fieldset>-->
<label>
<span>
<input type="text" name="username" placeholder="Username" />
<i class="ace-icon fa fa-user"></i>
</span>
</label>
</br>
<label>
<span>
<input type="password" name="password" placeholder="Password" />
<i class="ace-icon fa fa-lock"></i>
</span>
</label>
</br>
<label>
<span>
<input class="vcode" name="vcode" placeholder="验证码" type="text" />
<i class="ace-icon fa fa-lock"></i>
</span>
</label>
</br>
<label><input type="text" onclick="createCode()" readonly="readonly" id="checkCode" class="unchanged" style="width: 100px" /></label><br />
<label><input class="submit" name="submit" type="submit" value="Login" /></label>
</form>
<?php echo $html;?>
</div><!-- /.widget-main -->
</div><!-- /.widget-body -->
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<script language="javascript" type="text/javascript">
var code; //在全局 定义验证码
function createCode() {
code = "";
var codeLength = 5;//验证码的长度
var checkCode = document.getElementById("checkCode");
var selectChar = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');//所有候选组成验证码的字符,当然也可以用中文的
for (var i = 0; i < codeLength; i++) {
var charIndex = Math.floor(Math.random() * 36);
code += selectChar[charIndex];
}
//alert(code);
if (checkCode) {
checkCode.className = "code";
checkCode.value = code;
}
}
function validate() {
var inputCode = document.querySelector('#bf_client .vcode').value;
if (inputCode.length <= 0) {
alert("请输入验证码!");
return false;
} else if (inputCode != code) {
alert("验证码输入错误!");
createCode();//刷新验证码
return false;
}
else {
return true;
}
}
createCode();
</script>
<?php
include_once $PIKA_ROOT_DIR.'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/burteforce/bf_client.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/burteforce/bf_client.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 2922
} | 894 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "dir.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR . 'header.php';
$html='';
if(isset($_GET['title'])){
$filename=$_GET['title'];
//这里直接把传进来的内容进行了require(),造成问题
require "soup/$filename";
// echo $html;
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="dir.php">目录遍历</a>
</li>
<li class="active">../../</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="先好好读一下这两篇小短文在继续学习吧..">
点一下提示~
</a>
</div>
<div class="page-content">
<div id="dt_main">
<p class="dt_title">(1)it's time to get up!</p>
<a class="dt_title" href="dir_list.php?title=jarheads.php">we're jarheads!</a>
<p class="dt_title">(2)it's time to say goodbye!</p>
<a class="dt_title" href="dir_list.php?title=truman.php">Truman's word!</a>
</div>
<br />
<br />
<div>
<?php echo $html;?>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/dir/dir_list.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/dir/dir_list.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1179
} | 895 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "sqli_blind_t.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','','','','','','','','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR . 'header.php';
include_once $PIKA_ROOT_DIR . "inc/config.inc.php";
include_once $PIKA_ROOT_DIR . "inc/function.php";
include_once $PIKA_ROOT_DIR . "inc/mysql.inc.php";
$link=connect();
$html='';
if(isset($_GET['submit']) && $_GET['name']!=null){
$name=$_GET['name'];//这里没有做任何处理,直接拼到select里面去了
$query="select id,email from member where username='$name'";//这里的变量是字符型,需要考虑闭合
$result=mysqli_query($link, $query);//mysqi_query不打印错误描述
// $result=execute($link, $query);
// $html.="<p class='notice'>i don't care who you are!</p>";
if($result && mysqli_num_rows($result)==1){
while($data=mysqli_fetch_assoc($result)){
$id=$data['id'];
$email=$data['email'];
//这里不管输入啥,返回的都是一样的信息,所以更加不好判断
$html.="<p class='notice'>i don't care who you are!</p>";
}
}else{
$html.="<p class='notice'>i don't care who you are!</p>";
}
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="../sqli.php">sqli</a>
</li>
<li class="active">基于时间的盲注</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="admin/123456">
点一下提示~
</a>
</div>
<div class="page-content">
<div id="sqli_main">
<p class="sqli_title">what's your username?</p>
<form method="get">
<input class="sqli_in" type="text" name="name" />
<input class="sqli_submit" type="submit" name="submit" value="查询" />
</form>
<?php echo $html;?>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_blind_t.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/sqli/sqli_blind_t.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1517
} | 896 |
<?php
$html = <<<A
<br>
<pre>
假如生活欺骗了你
作者:普希金
假如生活欺骗了你,
不要悲伤,不要心急!
忧郁的日子里须要镇静:
相信吧,快乐的日子将会来临!
心儿永远向往着未来;
现在却常是忧郁。
一切都是瞬息,一切都将会过去;
而那过去了的,就会成为亲切的怀恋。
</pre>
A;
echo $html;
| zhuifengshaonianhanlu/pikachu/vul/ssrf/ssrf_info/info1.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/ssrf/ssrf_info/info1.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 269
} | 897 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "unsafedownload.php"){
$ACTIVE = array('','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','active open','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR . 'header.php';
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="unsafedownload.php">unsafe filedownload</a>
</li>
<li class="active">概述</li>
</ul><!-- /.breadcrumb -->
</div>
<div class="page-content">
<div id="vul_info">
<dl>
<dt class="vul_title">不安全的文件下载概述</dt>
<dd class="vul_detail">
文件下载功能在很多web系统上都会出现,一般我们当点击下载链接,便会向后台发送一个下载请求,一般这个请求会包含一个需要下载的文件名称,后台在收到请求后
会开始执行下载代码,将该文件名对应的文件response给浏览器,从而完成下载。
如果后台在收到请求的文件名后,将其直接拼进下载文件的路径中而不对其进行安全判断的话,则可能会引发不安全的文件下载漏洞。<br />
此时如果 攻击者提交的不是一个程序预期的的文件名,而是一个精心构造的路径(比如../../../etc/passwd),则很有可能会直接将该指定的文件下载下来。
从而导致后台敏感信息(密码文件、源代码等)被下载。
</dd>
<dd class="vul_detail">
所以,在设计文件下载功能时,如果下载的目标文件是由前端传进来的,则一定要对传进来的文件进行安全考虑。
切记:所有与前端交互的数据都是不安全的,不能掉以轻心!
</dd>
<dd class="vul_detail">
你可以通过“Unsafe file download”对应的测试栏目,来进一步的了解该漏洞。
</dd>
</dl>
</div>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR . 'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/unsafedownload/unsafedownload.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/unsafedownload/unsafedownload.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1862
} | 898 |
<?php
/**
* Created by runner.han
* There is nothing new under the sun
*/
$SELF_PAGE = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);
if ($SELF_PAGE = "xss_dom.php"){
$ACTIVE = array('','','','','','','','active open','','','','','active','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','');
}
$PIKA_ROOT_DIR = "../../";
include_once $PIKA_ROOT_DIR.'header.php';
include_once $PIKA_ROOT_DIR."inc/config.inc.php";
include_once $PIKA_ROOT_DIR."inc/mysql.inc.php";
$html='';
if(isset($_GET['text'])){
$html.= "<a href='#' onclick='domxss()'>有些费尽心机想要忘记的事情,后来真的就忘掉了</a>";
}
?>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs ace-save-state" id="breadcrumbs">
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="xss.php">xss</a>
</li>
<li class="active">DOM型xss</li>
</ul><!-- /.breadcrumb -->
<a href="#" style="float:right" data-container="body" data-toggle="popover" data-placement="bottom" title="tips(再点一下关闭)"
data-content="dom型XSS是鸡肋吗?">
点一下提示~
</a>
</div>
<div class="page-content">
<div id="xssd_main">
<script>
function domxss(){
var str = window.location.search;
var txss = decodeURIComponent(str.split("text=")[1]);
var xss = txss.replace(/\+/g,' ');
// alert(xss);
document.getElementById("dom").innerHTML = "<a href='"+xss+"'>就让往事都随风,都随风吧</a>";
}
//试试:'><img src="#" onmouseover="alert('xss')">
//试试:' onclick="alert('xss')">,闭合掉就行
</script>
<!--<a href="" onclick=('xss')>-->
<form method="get">
<input id="text" name="text" type="text" value="" />
<input id="submit" type="submit" value="请说出你的伤心往事"/>
</form>
<div id="dom"></div>
</div>
<?php echo $html;?>
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<?php
include_once $PIKA_ROOT_DIR.'footer.php';
?>
| zhuifengshaonianhanlu/pikachu/vul/xss/xss_dom_x.php/0 | {
"file_path": "zhuifengshaonianhanlu/pikachu/vul/xss/xss_dom_x.php",
"repo_id": "zhuifengshaonianhanlu",
"token_count": 1543
} | 899 |