CCMain.m 250 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotosCameraUpload.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "NCBridgeSwift.h"
  35. #define alertCreateFolder 1
  36. #define alertCreateFolderCrypto 2
  37. #define alertRename 3
  38. #define alertOfflineFolder 4
  39. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate>
  40. {
  41. tableMetadata *_metadata;
  42. BOOL _isRoot;
  43. BOOL _isViewDidLoad;
  44. BOOL _isOfflineServerUrl;
  45. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  46. BOOL _isSelectedMode;
  47. NSMutableArray *_selectedMetadatas;
  48. NSMutableArray *_queueSelector;
  49. NSUInteger _numSelectedMetadatas;
  50. UIImageView *_ImageTitleHomeCryptoCloud;
  51. UIView *_reMenuBackgroundView;
  52. UITapGestureRecognizer *_singleFingerTap;
  53. NSString *_directoryGroupBy;
  54. NSString *_directoryOrder;
  55. NSUInteger _failedAttempts;
  56. NSDate *_lockUntilDate;
  57. NSString *_fatherPermission;
  58. UIRefreshControl *_refreshControl;
  59. UIDocumentInteractionController *_docController;
  60. CCHud *_hud;
  61. CCHud *_hudDeterminate;
  62. // Datasource
  63. CCSectionDataSourceMetadata *_sectionDataSource;
  64. NSDate *_dateReadDataSource;
  65. // Search
  66. BOOL _isSearchMode;
  67. NSString *_searchFileName;
  68. NSMutableArray *_searchResultMetadatas;
  69. NSString *_depth;
  70. NSString *_noFilesSearchTitle;
  71. NSString *_noFilesSearchDescription;
  72. // Login
  73. CCLoginWeb *_loginWeb;
  74. CCLogin *_loginVC;
  75. }
  76. @end
  77. @implementation CCMain
  78. #pragma --------------------------------------------------------------------------------------------
  79. #pragma mark ===== Init =====
  80. #pragma --------------------------------------------------------------------------------------------
  81. - (id)initWithCoder:(NSCoder *)aDecoder
  82. {
  83. if (self = [super initWithCoder:aDecoder]) {
  84. _directoryOrder = [CCUtility getOrderSettings];
  85. _directoryGroupBy = [CCUtility getGroupBySettings];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  90. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  91. }
  92. return self;
  93. }
  94. #pragma --------------------------------------------------------------------------------------------
  95. #pragma mark ===== View =====
  96. #pragma --------------------------------------------------------------------------------------------
  97. - (void)viewDidLoad
  98. {
  99. [super viewDidLoad];
  100. // init object
  101. _metadata = [tableMetadata new];
  102. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  104. _selectedMetadatas = [NSMutableArray new];
  105. _queueSelector = [NSMutableArray new];
  106. _sectionDataSource = [CCSectionDataSourceMetadata new];
  107. _isViewDidLoad = YES;
  108. _fatherPermission = @"";
  109. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  110. _searchResultMetadatas = [NSMutableArray new];
  111. _searchFileName = @"";
  112. _depth = @"0";
  113. _noFilesSearchTitle = @"";
  114. _noFilesSearchDescription = @"";
  115. // delegate
  116. self.tableView.delegate = self;
  117. self.tableView.tableFooterView = [UIView new];
  118. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  119. self.tableView.emptyDataSetDelegate = self;
  120. self.tableView.emptyDataSetSource = self;
  121. self.searchController.delegate = self;
  122. self.searchController.searchBar.delegate = self;
  123. [[CCNetworking sharedNetworking] settingDelegate:self];
  124. // Custom Cell
  125. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  126. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  127. // long press recognizer TableView
  128. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  129. [self.tableView addGestureRecognizer:longPressRecognizer];
  130. // Pull-to-Refresh
  131. [self createRefreshControl];
  132. // Register for 3D Touch Previewing if available
  133. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  134. {
  135. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  136. }
  137. // Back Button
  138. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  139. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  140. // reMenu Background
  141. _reMenuBackgroundView = [[UIView alloc] init];
  142. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  143. // if this is not Main (the Main uses inizializeMain)
  144. if (_isRoot == NO && app.activeAccount.length > 0) {
  145. // Settings this folder & delegate & Loading datasource
  146. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  147. // Load Datasource
  148. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  149. // Read Folder
  150. [self readFolderWithForced:NO serverUrl:_serverUrl];
  151. }
  152. // Title
  153. [self setTitle];
  154. // Search
  155. self.definesPresentationContext = YES;
  156. self.searchController.searchResultsUpdater = self;
  157. self.searchController.dimsBackgroundDuringPresentation = NO;
  158. self.tableView.tableHeaderView = self.searchController.searchBar;
  159. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  160. [self.searchController.searchBar sizeToFit];
  161. self.searchController.searchBar.delegate = self;
  162. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  163. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  164. if (_isRoot)
  165. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil), nil];
  166. else
  167. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_sub_folder_",nil), nil];
  168. } else {
  169. self.searchController.searchBar.scopeButtonTitles = nil;
  170. }
  171. // Hide Search Filed on Load
  172. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  173. }
  174. // Apparirà
  175. - (void)viewWillAppear:(BOOL)animated
  176. {
  177. [super viewWillAppear:animated];
  178. // test
  179. if (app.activeAccount.length == 0)
  180. return;
  181. // Settings this folder & delegate & Loading datasource
  182. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  183. [[CCNetworking sharedNetworking] settingDelegate:self];
  184. // Color
  185. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  186. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  187. if (_isSelectedMode)
  188. [self setUINavigationBarSelected];
  189. else
  190. [self setUINavigationBarDefault];
  191. // Plus Button
  192. [app plusButtonVisibile:true];
  193. }
  194. // E' arrivato
  195. - (void)viewDidAppear:(BOOL)animated
  196. {
  197. [super viewDidAppear:animated];
  198. // Active Main
  199. app.activeMain = self;
  200. // Test viewDidLoad
  201. if (_isViewDidLoad) {
  202. _isViewDidLoad = NO;
  203. } else {
  204. if (app.activeAccount.length > 0) {
  205. // Load Datasource
  206. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  207. // Read Folder
  208. [self readFolderWithForced:NO serverUrl:_serverUrl];
  209. }
  210. }
  211. // Title
  212. [self setTitle];
  213. }
  214. - (void)viewWillDisappear:(BOOL)animated
  215. {
  216. [super viewWillDisappear:animated];
  217. [self closeAllMenu];
  218. }
  219. - (void)didReceiveMemoryWarning
  220. {
  221. [super didReceiveMemoryWarning];
  222. // Dispose of any resources that can be recreated.
  223. }
  224. - (BOOL)prefersStatusBarHidden
  225. {
  226. return NO;
  227. }
  228. // detect scroll for remove keyboard in search mode
  229. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  230. {
  231. if (_isSearchMode && scrollView == self.tableView) {
  232. [self.searchController.searchBar endEditing:YES];
  233. }
  234. }
  235. - (void)changeTheming
  236. {
  237. if (self.isViewLoaded && self.view.window)
  238. [app changeTheming:self];
  239. // Refresh control
  240. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  241. // Reload Table View
  242. [self.tableView reloadData];
  243. }
  244. #pragma --------------------------------------------------------------------------------------------
  245. #pragma mark ===== Initizlize Mail =====
  246. #pragma --------------------------------------------------------------------------------------------
  247. - (void)initializeMain:(NSNotification *)notification
  248. {
  249. _directoryGroupBy = nil;
  250. _directoryOrder = nil;
  251. _dateReadDataSource = nil;
  252. // test
  253. if (app.activeAccount.length == 0)
  254. return;
  255. if ([app.listMainVC count] == 0 || _isRoot) {
  256. // This is Root
  257. _isRoot = YES;
  258. // Crypto Mode
  259. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  260. app.isCryptoCloudMode = NO;
  261. } else {
  262. app.isCryptoCloudMode = YES;
  263. }
  264. // go Home
  265. [self.navigationController popToRootViewControllerAnimated:NO];
  266. // Remove search mode
  267. [self cancelSearchBar];
  268. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  269. _isFolderEncrypted = NO;
  270. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  271. // add list
  272. [app.listMainVC setObject:self forKey:_serverUrl];
  273. // setting Networking
  274. [[CCNetworking sharedNetworking] settingDelegate:self];
  275. [[CCNetworking sharedNetworking] settingAccount];
  276. // populate shared Link & User variable
  277. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  278. if (results) {
  279. app.sharesLink = results[0];
  280. app.sharesUserAndGroup = results[1];
  281. }
  282. // Setting Theming
  283. [app settingThemingColorBrand];
  284. // Load Datasource
  285. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  286. // Load Folder
  287. [self readFolderWithForced:NO serverUrl:_serverUrl];
  288. // Load photo datasorce
  289. if (app.activePhotosCameraUpload)
  290. [app.activePhotosCameraUpload reloadDatasourceForced];
  291. // remove all of detail
  292. if (app.activeDetail)
  293. [app.activeDetail removeAllView];
  294. // remove all Notification Messages
  295. [app.listOfNotifications removeAllObjects];
  296. // home main
  297. app.homeMain = self;
  298. // Initializations
  299. [app applicationInitialized];
  300. } else {
  301. // reload datasource
  302. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  303. }
  304. }
  305. #pragma --------------------------------------------------------------------------------------------
  306. #pragma mark ==== DZNEmptyDataSetSource ====
  307. #pragma --------------------------------------------------------------------------------------------
  308. /*
  309. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  310. {
  311. if(_isSearchMode)
  312. return NO;
  313. else
  314. return YES;
  315. }
  316. */
  317. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  318. {
  319. return YES;
  320. }
  321. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  322. {
  323. return [UIColor whiteColor];
  324. }
  325. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  326. {
  327. if (_isSearchMode)
  328. return [UIImage imageNamed:@"searchBig"];
  329. else
  330. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  331. }
  332. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  333. {
  334. NSString *text;
  335. if (_isSearchMode)
  336. text = _noFilesSearchTitle;
  337. else
  338. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  339. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  340. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  341. }
  342. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  343. {
  344. NSString *text;
  345. if (_isSearchMode)
  346. text = _noFilesSearchDescription;
  347. else
  348. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  349. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  350. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  351. paragraph.alignment = NSTextAlignmentCenter;
  352. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  353. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  354. }
  355. #pragma --------------------------------------------------------------------------------------------
  356. #pragma mark ===== AlertView =====
  357. #pragma --------------------------------------------------------------------------------------------
  358. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  359. {
  360. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  361. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text folderCameraUpload:NO];
  362. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  363. if (alertView.tag == alertRename && buttonIndex == 1) {
  364. if ([_metadata.model isEqualToString:@"note"]) {
  365. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  366. } else {
  367. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  368. }
  369. }
  370. if (alertView.tag == alertOfflineFolder && buttonIndex == 1) {
  371. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  372. NSString *dir = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  373. [[CCSynchronize sharedSynchronize] addOfflineFolder:dir];
  374. [self performSelector:@selector(reloadDatasource) withObject:nil];
  375. }
  376. }
  377. // accept only number char > 0
  378. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  379. {
  380. /* Retrieve a text field at an index -
  381. raises NSRangeException when textFieldIndex is out-of-bounds.
  382. The field at index 0 will be the first text field
  383. (the single field or the login field),
  384. The field at index 1 will be the password field. */
  385. /*
  386. 1> Get the Text Field in alertview
  387. 2> Get the text of that Text Field
  388. 3> Verify that text length
  389. 4> return YES or NO Based on the length
  390. */
  391. if (alertView.tag == alertOfflineFolder) return YES;
  392. else return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  393. }
  394. #pragma --------------------------------------------------------------------------------------------
  395. #pragma mark ===== Graphic Window =====
  396. #pragma --------------------------------------------------------------------------------------------
  397. - (void)createRefreshControl
  398. {
  399. _refreshControl = [UIRefreshControl new];
  400. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  401. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  402. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  403. [self setRefreshControl:_refreshControl];
  404. }
  405. - (void)deleteRefreshControl
  406. {
  407. [_refreshControl endRefreshing];
  408. self.refreshControl = nil;
  409. }
  410. - (void)refreshControlTarget
  411. {
  412. [self readFolderWithForced:YES serverUrl:_serverUrl];
  413. // Actuate `Peek` feedback (weak boom)
  414. AudioServicesPlaySystemSound(1519);
  415. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  416. }
  417. - (void)setTitle
  418. {
  419. // Color text self.navigationItem.title
  420. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  421. if (_isSelectedMode) {
  422. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  423. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  424. self.navigationItem.titleView = nil;
  425. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  426. } else {
  427. // we are in home : LOGO BRAND
  428. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  429. self.navigationItem.title = nil;
  430. if ([app.reachability isReachable] == NO)
  431. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  432. else
  433. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  434. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  435. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  436. [singleTap setNumberOfTapsRequired:1];
  437. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  438. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  439. } else {
  440. self.navigationItem.title = _titleMain;
  441. }
  442. }
  443. }
  444. - (void)setUINavigationBarDefault
  445. {
  446. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  447. UIBarButtonItem *buttonMore, *buttonNotification;
  448. // =
  449. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  450. buttonMore.enabled = true;
  451. // <
  452. self.navigationController.navigationBar.hidden = NO;
  453. // Notification
  454. if ([app.listOfNotifications count] > 0) {
  455. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  456. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  457. buttonNotification.enabled = true;
  458. }
  459. if (buttonNotification)
  460. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  461. else
  462. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  463. self.navigationItem.leftBarButtonItem = nil;
  464. }
  465. - (void)setUINavigationBarSelected
  466. {
  467. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  468. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  469. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  470. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  471. self.navigationItem.leftBarButtonItem = leftButton;
  472. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  473. }
  474. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  475. {
  476. [self closeAllMenu];
  477. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  478. }];
  479. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  480. }
  481. - (void)cancelSelect
  482. {
  483. [self tableViewSelect:NO];
  484. [app.reSelectMenu close];
  485. }
  486. - (void)closeAllMenu
  487. {
  488. // close Menu
  489. [app.reSelectMenu close];
  490. [app.reMainMenu close];
  491. // Close Menu Logo
  492. [CCMenuAccount dismissMenu];
  493. }
  494. #pragma --------------------------------------------------------------------------------------------
  495. #pragma mark ===== Document Picker =====
  496. #pragma --------------------------------------------------------------------------------------------
  497. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  498. {
  499. NSLog(@"Cancelled");
  500. }
  501. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  502. {
  503. NSLog(@"Cancelled");
  504. }
  505. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  506. {
  507. documentPicker.delegate = self;
  508. [self presentViewController:documentPicker animated:YES completion:nil];
  509. }
  510. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  511. {
  512. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  513. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  514. __block NSError *error;
  515. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  516. NSString *fileName = [url lastPathComponent];
  517. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  518. NSData *data = [NSData dataWithContentsOfURL:newURL];
  519. if (data && error == nil) {
  520. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  521. // Upload File
  522. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  523. } else {
  524. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  525. }
  526. } else {
  527. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  528. }
  529. }];
  530. }
  531. }
  532. - (void)openImportDocumentPicker
  533. {
  534. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  535. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  536. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  537. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  538. documentProviderMenu.delegate = self;
  539. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  540. }
  541. #pragma --------------------------------------------------------------------------------------------
  542. #pragma mark ===== Assets Picker =====
  543. #pragma --------------------------------------------------------------------------------------------
  544. - (void)openAssetsPickerController
  545. {
  546. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  547. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  548. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  549. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  550. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  551. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  552. dispatch_async(dispatch_get_main_queue(), ^{
  553. // init picker
  554. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  555. // set delegate
  556. picker.delegate = self;
  557. // to show selection order
  558. //picker.showsSelectionIndex = YES;
  559. // to present picker as a form sheet in iPad
  560. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  561. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  562. // present picker
  563. [self presentViewController:picker animated:YES completion:nil];
  564. });
  565. }];
  566. }
  567. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  568. {
  569. [picker dismissViewControllerAnimated:YES completion:^{
  570. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  571. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  572. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  573. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  574. //navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  575. [self presentViewController:navigationController animated:YES completion:nil];
  576. }];
  577. }
  578. #pragma --------------------------------------------------------------------------------------------
  579. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  580. #pragma --------------------------------------------------------------------------------------------
  581. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  582. {
  583. // evitiamo il rimando della eventuale photo e/o video
  584. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  585. if (tableAccount.cameraUpload) {
  586. [[NCManageDatabase sharedInstance] setAccountCameraUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  587. [[NCManageDatabase sharedInstance] setAccountCameraUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  588. }
  589. }
  590. #pragma --------------------------------------------------------------------------------------------
  591. #pragma mark ===== UnZipFile =====
  592. #pragma --------------------------------------------------------------------------------------------
  593. - (void)unZipFile:(NSString *)fileID
  594. {
  595. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  596. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  597. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  598. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  599. dispatch_async(dispatch_get_main_queue(), ^{
  600. float progress = (float) entryNumber / (float)total;
  601. [_hudDeterminate progress:progress];
  602. });
  603. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  604. dispatch_async(dispatch_get_main_queue(), ^{
  605. [_hudDeterminate hideHud];
  606. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  607. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  608. });
  609. }];
  610. });
  611. }
  612. #pragma --------------------------------------------------------------------------------------------
  613. #pragma mark ===== Create New (OpenModel) =====
  614. #pragma --------------------------------------------------------------------------------------------
  615. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  616. {
  617. UIViewController *viewController;
  618. NSString *fileName, *uuid, *fileID, *serverUrl;
  619. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  620. [self.tableView deselectRowAtIndexPath:index animated:NO];
  621. if (isnew) {
  622. fileName = nil;
  623. uuid = [CCUtility getUUID];
  624. fileID = nil;
  625. serverUrl = _serverUrl;
  626. } else {
  627. fileName = _metadata.fileName;
  628. uuid = _metadata.uuid;
  629. fileID = _metadata.fileID;
  630. serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  631. }
  632. if ([tipo isEqualToString:@"cartadicredito"])
  633. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  634. if ([tipo isEqualToString:@"bancomat"])
  635. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  636. if ([tipo isEqualToString:@"contocorrente"])
  637. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  638. if ([tipo isEqualToString:@"accountweb"])
  639. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  640. if ([tipo isEqualToString:@"patenteguida"])
  641. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  642. if ([tipo isEqualToString:@"cartaidentita"])
  643. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  644. if ([tipo isEqualToString:@"passaporto"])
  645. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  646. if ([tipo isEqualToString:@"note"]) {
  647. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  648. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  649. [self presentViewController:navigationController animated:YES completion:nil];
  650. } else {
  651. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  652. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  653. [self presentViewController:navigationController animated:YES completion:nil];
  654. }
  655. }
  656. // New folder or new photo or video
  657. - (void)returnCreate:(NSInteger)type
  658. {
  659. switch (type) {
  660. /* PLAIN */
  661. case k_returnCreateFolderPlain: {
  662. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  663. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  664. alertView.tag = alertCreateFolder;
  665. [alertView show];
  666. }
  667. break;
  668. case k_returnCreateFotoVideoPlain: {
  669. _isPickerCriptate = false;
  670. [self openAssetsPickerController];
  671. }
  672. break;
  673. case k_returnCreateFilePlain: {
  674. _isPickerCriptate = false;
  675. [self openImportDocumentPicker];
  676. }
  677. break;
  678. /* ENCRYPTED */
  679. case k_returnCreateFolderEncrypted: {
  680. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  681. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  682. alertView.tag = alertCreateFolderCrypto;
  683. [alertView show];
  684. }
  685. break;
  686. case k_returnCreateFotoVideoEncrypted: {
  687. _isPickerCriptate = true;
  688. [self openAssetsPickerController];
  689. }
  690. break;
  691. case k_returnCreateFileEncrypted: {
  692. _isPickerCriptate = true;
  693. [self openImportDocumentPicker];
  694. }
  695. break;
  696. /* UTILITY */
  697. case k_returnNote:
  698. [self openModel:@"note" isNew:true];
  699. break;
  700. case k_returnAccountWeb:
  701. [self openModel:@"accountweb" isNew:true];
  702. break;
  703. /* BANK */
  704. case k_returnCartaDiCredito:
  705. [self openModel:@"cartadicredito" isNew:true];
  706. break;
  707. case k_returnBancomat:
  708. [self openModel:@"bancomat" isNew:true];
  709. break;
  710. case k_returnContoCorrente:
  711. [self openModel:@"contocorrente" isNew:true];
  712. break;
  713. /* DOCUMENT */
  714. case k_returnPatenteGuida:
  715. [self openModel:@"patenteguida" isNew:true];
  716. break;
  717. case k_returnCartaIdentita:
  718. [self openModel:@"cartaidentita" isNew:true];
  719. break;
  720. case k_returnPassaporto:
  721. [self openModel:@"passaporto" isNew:true];
  722. break;
  723. }
  724. }
  725. #pragma --------------------------------------------------------------------------------------------
  726. #pragma mark ===== Save selected File =====
  727. #pragma --------------------------------------------------------------------------------------------
  728. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  729. {
  730. if (error)
  731. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  732. else
  733. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  734. }
  735. - (void)saveSelectedFiles
  736. {
  737. NSLog(@"[LOG] Start download selected files ...");
  738. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  739. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  740. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  741. for (tableMetadata *metadata in metadatas) {
  742. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  743. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  744. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  745. }
  746. }
  747. [_hud hideHud];
  748. });
  749. [self tableViewSelect:NO];
  750. }
  751. #pragma --------------------------------------------------------------------------------------------
  752. #pragma mark ===== Change Password =====
  753. #pragma --------------------------------------------------------------------------------------------
  754. - (void) loginSuccess:(NSInteger)loginType
  755. {
  756. [self readFolderWithForced:YES serverUrl:_serverUrl];
  757. }
  758. - (void)changePasswordAccount
  759. {
  760. // Brand
  761. if ([NCBrandOptions sharedInstance].use_login_web) {
  762. _loginWeb = [CCLoginWeb new];
  763. _loginWeb.delegate = self;
  764. _loginWeb.loginType = loginModifyPasswordUser;
  765. dispatch_async(dispatch_get_main_queue(), ^ {
  766. [_loginWeb presentModalWithDefaultTheme:self];
  767. });
  768. } else {
  769. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  770. _loginVC.delegate = self;
  771. _loginVC.loginType = loginModifyPasswordUser;
  772. [self presentViewController:_loginVC animated:YES completion:nil];
  773. }
  774. }
  775. #pragma mark -
  776. #pragma --------------------------------------------------------------------------------------------
  777. #pragma mark ===== Peek & Pop =====
  778. #pragma --------------------------------------------------------------------------------------------
  779. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  780. {
  781. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  782. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  783. if (metadata.thumbnailExists && !metadata.cryptated) {
  784. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  785. if (cell) {
  786. previewingContext.sourceRect = cell.frame;
  787. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  788. vc.delegate = self;
  789. vc.metadata = metadata;
  790. return vc;
  791. }
  792. }
  793. return nil;
  794. }
  795. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  796. {
  797. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  798. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  799. }
  800. #pragma mark -
  801. #pragma --------------------------------------------------------------------------------------------
  802. #pragma mark ==== External Sites ====
  803. #pragma --------------------------------------------------------------------------------------------
  804. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  805. {
  806. [[NCManageDatabase sharedInstance] deleteExternalSites];
  807. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  808. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  809. }
  810. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  811. {
  812. NSLog(@"[LOG] No External Sites found");
  813. }
  814. #pragma --------------------------------------------------------------------------------------------
  815. #pragma mark ==== Activity ====
  816. #pragma --------------------------------------------------------------------------------------------
  817. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  818. {
  819. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  820. // Reload Activity Data Source
  821. [app.activeActivity reloadDatasource];
  822. }
  823. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  824. {
  825. NSLog(@"[LOG] No Activity found");
  826. }
  827. #pragma --------------------------------------------------------------------------------------------
  828. #pragma mark ==== Notification ====
  829. #pragma --------------------------------------------------------------------------------------------
  830. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  831. {
  832. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  833. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  834. // Order by date
  835. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  836. OCNotifications *notification1 = obj1, *notification2 = obj2;
  837. return [notification2.date compare: notification1.date];
  838. }];
  839. // verify if listOfNotifications is changed
  840. NSString *old = @"", *new = @"";
  841. for (OCNotifications *notification in listOfNotifications)
  842. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  843. for (OCNotifications *notification in appDelegate.listOfNotifications)
  844. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  845. if (![new isEqualToString:old]) {
  846. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  847. // reload Notification view
  848. dispatch_async(dispatch_get_main_queue(), ^{
  849. [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationReloadData" object:nil];
  850. });
  851. }
  852. // Update NavigationBar
  853. if (!_isSelectedMode) {
  854. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  855. }
  856. });
  857. }
  858. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  859. {
  860. // Update NavigationBar
  861. if (!_isSelectedMode)
  862. [self setUINavigationBarDefault];
  863. }
  864. - (void)viewNotification
  865. {
  866. if ([app.listOfNotifications count] > 0) {
  867. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  868. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  869. [self presentViewController:notificationVC animated:YES completion:nil];
  870. }
  871. }
  872. #pragma --------------------------------------------------------------------------------------------
  873. #pragma mark ==== User Profile ====
  874. #pragma --------------------------------------------------------------------------------------------
  875. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  876. {
  877. if (errorCode == 401)
  878. [self changePasswordAccount];
  879. }
  880. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  881. {
  882. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  883. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  884. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  885. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  886. if (avatar)
  887. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  888. else
  889. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  890. dispatch_async(dispatch_get_main_queue(), ^{
  891. [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserProfile" object:nil];
  892. });
  893. });
  894. }
  895. #pragma --------------------------------------------------------------------------------------------
  896. #pragma mark ==== Capabilities ====
  897. #pragma --------------------------------------------------------------------------------------------
  898. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  899. {
  900. // Change Theming color
  901. [app settingThemingColorBrand];
  902. if (errorCode == 401)
  903. [self changePasswordAccount];
  904. }
  905. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  906. {
  907. // Update capabilities db
  908. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  909. // ------ THEMING -----------------------------------------------------------------------
  910. // Download Theming Background & Change Theming color
  911. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  912. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  913. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  914. if (themingBackground)
  915. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  916. else
  917. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  918. }
  919. dispatch_async(dispatch_get_main_queue(), ^{
  920. [app settingThemingColorBrand];
  921. });
  922. });
  923. // ------ SEARCH ------------------------------------------------------------------------
  924. // Search bar if change version
  925. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  926. [self cancelSearchBar];
  927. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  928. if (capabilities.versionMajor >= 12) {
  929. if (_isRoot)
  930. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_all_folders_",nil);
  931. else
  932. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_sub_folder_",nil);
  933. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),self.searchController.searchBar.placeholder, nil];
  934. } else {
  935. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  936. self.searchController.searchBar.scopeButtonTitles = nil;
  937. }
  938. _depth = @"0";
  939. });
  940. }
  941. // ------ GET SERVICE SERVER ------------------------------------------------------------
  942. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  943. // Read External Sites
  944. if (capabilities.isExternalSitesServerEnabled) {
  945. metadataNet.action = actionGetExternalSitesServer;
  946. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  947. }
  948. // Read Share
  949. if (capabilities.isFilesSharingAPIEnabled) {
  950. [app.sharesID removeAllObjects];
  951. metadataNet.action = actionReadShareServer;
  952. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  953. }
  954. // Read Notification
  955. metadataNet.action = actionGetNotificationServer;
  956. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  957. // Read User Profile
  958. metadataNet.action = actionGetUserProfile;
  959. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  960. // Read Activity
  961. metadataNet.action = actionGetActivityServer;
  962. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  963. }
  964. #pragma mark -
  965. #pragma --------------------------------------------------------------------------------------------
  966. #pragma mark ==== Request Server Information ====
  967. #pragma --------------------------------------------------------------------------------------------
  968. - (void)requestServerCapabilities
  969. {
  970. // test
  971. if (app.activeAccount.length == 0)
  972. return;
  973. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  974. metadataNet.action = actionGetCapabilities;
  975. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  976. }
  977. #pragma mark -
  978. #pragma --------------------------------------------------------------------------------------------
  979. #pragma mark ==== Download Thumbnail Delegate ====
  980. #pragma --------------------------------------------------------------------------------------------
  981. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  982. {
  983. __block CCCellMain *cell;
  984. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  985. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  986. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  987. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  988. if (cell.fileImageView.image == nil) {
  989. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  990. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  991. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  992. });
  993. }
  994. }
  995. }
  996. #pragma --------------------------------------------------------------------------------------------
  997. #pragma mark ==== Download ====
  998. #pragma --------------------------------------------------------------------------------------------
  999. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1000. {
  1001. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount]];
  1002. // File do not exists on server, remove in local
  1003. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  1004. [CCCoreData deleteFile:metadata serverUrl:serverUrl directoryUser:app.directoryUser activeAccount:app.activeAccount];
  1005. }
  1006. if ([selector isEqualToString:selectorLoadViewImage]) {
  1007. dispatch_async(dispatch_get_main_queue(), ^{
  1008. // Updating Detail
  1009. if (app.activeDetail)
  1010. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  1011. // Updating Photos
  1012. if (app.activePhotosCameraUpload)
  1013. [app.activePhotosCameraUpload downloadFileFailure:errorCode];
  1014. });
  1015. } else {
  1016. if (errorCode != kCFURLErrorCancelled)
  1017. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1018. }
  1019. [self reloadDatasource:serverUrl fileID:fileID selector:selector];
  1020. }
  1021. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1022. {
  1023. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1024. if (metadata == nil) return;
  1025. // Download
  1026. if ([selector isEqualToString:selectorDownloadFile]) {
  1027. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1028. }
  1029. // Synchronized
  1030. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1031. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1032. }
  1033. // add Favorite
  1034. if ([selector isEqualToString:selectorAddFavorite]) {
  1035. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1036. }
  1037. // add Offline
  1038. if ([selector isEqualToString:selectorAddOffline]) {
  1039. [CCCoreData setOfflineLocalEtag:metadata.fileID offline:YES activeAccount:app.activeAccount];
  1040. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1041. }
  1042. // encrypted file
  1043. if ([selector isEqualToString:selectorEncryptFile]) {
  1044. [self encryptedFile:metadata];
  1045. }
  1046. // decrypted file
  1047. if ([selector isEqualToString:selectorDecryptFile]) {
  1048. [self decryptedFile:metadata];
  1049. }
  1050. // open View File
  1051. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1052. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1053. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1054. [self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1055. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1056. selector = selectorOpenIn;
  1057. } else {
  1058. _metadata = metadata;
  1059. if ([self shouldPerformSegue])
  1060. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1061. }
  1062. }
  1063. // addLocal
  1064. if ([selector isEqualToString:selectorAddLocal]) {
  1065. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1066. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1067. [CCGraphics saveIcoWithEtag:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1068. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  1069. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1070. }
  1071. // Open with...
  1072. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1073. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1074. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1075. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1076. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1077. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1078. _docController.delegate = self;
  1079. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1080. }
  1081. // Save to Photo Album
  1082. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1083. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1084. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1085. // evitiamo il rimando photo
  1086. [[NCManageDatabase sharedInstance] setAccountCameraUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  1087. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1088. if (image)
  1089. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1090. else
  1091. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1092. }
  1093. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1094. // we avoid the cross-reference video
  1095. [[NCManageDatabase sharedInstance] setAccountCameraUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  1096. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1097. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1098. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1099. } else {
  1100. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1101. }
  1102. }
  1103. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1104. }
  1105. // Copy File
  1106. if ([selector isEqualToString:selectorLoadCopy]) {
  1107. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1108. [self copyFileToPasteboard:metadata];
  1109. }
  1110. // download and view a template
  1111. if ([selector isEqualToString:selectorLoadModelView]) {
  1112. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1113. [self openModel:metadata.model isNew:false];
  1114. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1115. }
  1116. //download file plist
  1117. if ([selector isEqualToString:selectorLoadPlist]) {
  1118. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1119. long countSelectorLoadPlist = 0;
  1120. for (NSOperation *operation in [app.netQueue operations]) {
  1121. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1122. countSelectorLoadPlist++;
  1123. }
  1124. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl]]) {
  1125. dispatch_async(dispatch_get_main_queue(), ^{
  1126. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1127. });
  1128. }
  1129. }
  1130. //selectorLoadViewImage
  1131. if ([selector isEqualToString:selectorLoadViewImage]) {
  1132. dispatch_async(dispatch_get_main_queue(), ^{
  1133. // Detail
  1134. if (app.activeDetail)
  1135. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1136. // Photos
  1137. if (app.activePhotosCameraUpload)
  1138. [app.activePhotosCameraUpload downloadFileSuccess:metadata];
  1139. });
  1140. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1141. }
  1142. // if exists postselector call self with selectorPost
  1143. if ([selectorPost length] > 0)
  1144. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1145. }
  1146. - (void)downloadSelectedFiles
  1147. {
  1148. NSLog(@"[LOG] Start download selected files ...");
  1149. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1150. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1151. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1152. for (tableMetadata *metadata in selectedMetadatas) {
  1153. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file]) {
  1154. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1155. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDownloadFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1156. }
  1157. }
  1158. [_hud hideHud];
  1159. });
  1160. [self tableViewSelect:NO];
  1161. }
  1162. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1163. {
  1164. NSArray *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", app.activeAccount, directoryID] sorted:nil ascending:NO];
  1165. for (tableMetadata *metadata in metadatas) {
  1166. if ([CCUtility isCryptoPlistString:metadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]] == NO && [metadata.session length] == 0) {
  1167. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1168. metadataNet.action = actionDownloadFile;
  1169. metadataNet.downloadData = NO;
  1170. metadataNet.downloadPlist = YES;
  1171. metadataNet.fileID = metadata.fileID;
  1172. metadataNet.selector = selectorLoadPlist;
  1173. metadataNet.serverUrl = serverUrl;
  1174. metadataNet.session = k_download_session_foreground;
  1175. metadataNet.taskStatus = k_taskStatusResume;
  1176. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1177. }
  1178. }
  1179. }
  1180. #pragma --------------------------------------------------------------------------------------------
  1181. #pragma mark ===== Upload new Photos/Videos =====
  1182. #pragma --------------------------------------------------------------------------------------------
  1183. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1184. {
  1185. // Automatic upload All
  1186. if([selector isEqualToString:selectorUploadAutomaticAll])
  1187. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1188. // Read File test do not exists
  1189. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1190. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  1191. // reUpload
  1192. if (metadata)
  1193. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1194. }
  1195. // Print error
  1196. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1197. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1198. }
  1199. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1200. }
  1201. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1202. {
  1203. // Automatic upload All
  1204. if([selector isEqualToString:selectorUploadAutomaticAll])
  1205. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1206. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1207. [self readFolderWithForced:YES serverUrl:serverUrl];
  1208. } else {
  1209. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1210. }
  1211. }
  1212. //
  1213. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1214. //
  1215. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1216. {
  1217. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1218. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1219. });
  1220. }
  1221. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1222. {
  1223. NSArray *assets = [arguments objectAtIndex:0];
  1224. NSString *serverUrl = [arguments objectAtIndex:1];
  1225. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1226. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1227. NSString *session = [arguments objectAtIndex:4];
  1228. NSString *folderPhotos = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathAndName:app.activeUrl];
  1229. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1230. // Create the folder for Photos & if request the subfolders
  1231. if (![app createFolderSubFolderAutomaticUploadFolderPhotos:folderPhotos useSubFolder:useSubFolder assets:assets selector:selectorUploadFile])
  1232. return;
  1233. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1234. for (PHAsset *asset in assets) {
  1235. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1236. NSDate *assetDate = asset.creationDate;
  1237. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1238. // Create serverUrl if use sub folder
  1239. if (useSubFolder) {
  1240. [formatter setDateFormat:@"yyyy"];
  1241. NSString *yearString = [formatter stringFromDate:assetDate];
  1242. [formatter setDateFormat:@"MM"];
  1243. NSString *monthString = [formatter stringFromDate:assetDate];
  1244. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  1245. }
  1246. // Check if is in upload
  1247. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1248. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:predicate sorted:nil ascending:NO];
  1249. if ([isRecordInSessions count] > 0) {
  1250. // next upload
  1251. continue;
  1252. } else {
  1253. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1254. metadataNet.action = actionReadFile;
  1255. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1256. metadataNet.cryptated = cryptated;
  1257. metadataNet.fileName = fileName;
  1258. metadataNet.priority = NSOperationQueuePriorityNormal;
  1259. metadataNet.session = session;
  1260. metadataNet.selector = selectorReadFileUploadFile;
  1261. metadataNet.serverUrl = serverUrl;
  1262. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1263. }
  1264. }
  1265. }
  1266. #pragma --------------------------------------------------------------------------------------------
  1267. #pragma mark ==== Read File ====
  1268. #pragma --------------------------------------------------------------------------------------------
  1269. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1270. {
  1271. // UploadFile
  1272. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1273. // File not exists
  1274. if (errorCode == 404) {
  1275. metadataNet.action = actionUploadAsset;
  1276. metadataNet.errorCode = 0;
  1277. metadataNet.selector = selectorUploadFile;
  1278. metadataNet.selectorPost = nil;
  1279. metadataNet.taskStatus = k_taskStatusResume;
  1280. if ([metadataNet.session containsString:@"wwan"])
  1281. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1282. else
  1283. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1284. } else {
  1285. // error ho many retry befor notification and go to on next asses
  1286. if (metadataNet.errorRetry < 3) {
  1287. // Retry read file
  1288. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1289. } else {
  1290. // STOP check file, view message error
  1291. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1292. }
  1293. }
  1294. }
  1295. }
  1296. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1297. {
  1298. // UploadFile
  1299. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1300. metadataNet.action = actionUploadAsset;
  1301. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1302. metadataNet.selector = selectorUploadFile;
  1303. metadataNet.selectorPost = nil;
  1304. metadataNet.taskStatus = k_taskStatusResume;
  1305. if ([metadataNet.session containsString:@"wwan"])
  1306. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1307. else
  1308. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1309. }
  1310. }
  1311. #pragma --------------------------------------------------------------------------------------------
  1312. #pragma mark ==== Read Folder ====
  1313. #pragma --------------------------------------------------------------------------------------------
  1314. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1315. {
  1316. // verify active user
  1317. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1318. [_hud hideHud];
  1319. [_refreshControl endRefreshing];
  1320. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1321. if (message && [record.account isEqualToString:metadataNet.account])
  1322. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1323. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1324. if (errorCode == 401)
  1325. [self changePasswordAccount];
  1326. }
  1327. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions fileID:(NSString *)fileID metadatas:(NSArray *)metadatas
  1328. {
  1329. // verify active user
  1330. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1331. if (![record.account isEqualToString:metadataNet.account])
  1332. return;
  1333. // save father e update permission
  1334. if(!_isSearchMode)
  1335. _fatherPermission = permissions;
  1336. NSArray *recordsInSessions;
  1337. if (_isSearchMode) {
  1338. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1339. } else {
  1340. [[NCManageDatabase sharedInstance] updateDirectoryFileID:metadataNet.serverUrl fileID:fileID];
  1341. [[NCManageDatabase sharedInstance] deleteMetadata:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID]];
  1342. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1343. [[NCManageDatabase sharedInstance] setDateReadDirectory:metadataNet.directoryID];
  1344. }
  1345. for (tableMetadata *metadata in metadatas) {
  1346. // type of file
  1347. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1348. // if crypto do not insert
  1349. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1350. // verify if the record encrypted has plist + crypto
  1351. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1352. BOOL isCryptoComplete = NO;
  1353. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1354. for (tableMetadata *completeMetadata in metadatas) {
  1355. if (completeMetadata.cryptated == NO) continue;
  1356. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1357. isCryptoComplete = YES;
  1358. break;
  1359. }
  1360. }
  1361. if (isCryptoComplete == NO) continue;
  1362. }
  1363. // verify if the record is in download/upload progress
  1364. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1365. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1366. // is in Download or Upload
  1367. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1368. continue;
  1369. }
  1370. }
  1371. // end test, insert in Database
  1372. [[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:app.activeUrl];
  1373. }
  1374. // read plist
  1375. if (!_isSearchMode)
  1376. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1377. // File is changed ??
  1378. if (!_isSearchMode)
  1379. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1380. // Search Mode
  1381. if (_isSearchMode)
  1382. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1383. // this is the same directory
  1384. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1385. // reload
  1386. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1387. // stoprefresh
  1388. [_refreshControl endRefreshing];
  1389. // Enable change user
  1390. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1391. [_hud hideHud];
  1392. }
  1393. }
  1394. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1395. {
  1396. // init control
  1397. if (!serverUrl || !app.activeAccount)
  1398. return;
  1399. // Search Mode
  1400. if (_isSearchMode) {
  1401. if (forced) {
  1402. [[NCManageDatabase sharedInstance] clearDateRead:serverUrl directoryID:nil];
  1403. _searchFileName = @""; // forced reload searchg
  1404. }
  1405. [self updateSearchResultsForSearchController:self.searchController];
  1406. return;
  1407. }
  1408. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPreficate:[NSPredicate predicateWithFormat:@"serverUrl = %@", serverUrl]];
  1409. NSString *directoryID = directory.directoryID;
  1410. // Is Directory Out Of Date ?
  1411. BOOL isDirectoryOutOfDate = false;
  1412. NSDateComponents *dateComponents = [NSDateComponents new];
  1413. [dateComponents setWeekday:k_dayForceReadFolder];
  1414. NSCalendar *calendar = [NSCalendar currentCalendar];
  1415. NSDate *datePlus = [calendar dateByAddingComponents:dateComponents toDate:directory.dateReadDirectory options:0];
  1416. NSDate *now = [NSDate date];
  1417. // usa la Cache se richiesto e se la data è entro X giorni dall'ultima volta che l'hai letta.
  1418. if ([now compare:datePlus] == NSOrderedDescending)
  1419. isDirectoryOutOfDate = true;
  1420. if (isDirectoryOutOfDate || forced) {
  1421. if (_refreshControl.isRefreshing == NO)
  1422. [_hud visibleIndeterminateHud];
  1423. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1424. metadataNet.action = actionReadFolder;
  1425. metadataNet.date = [NSDate date];
  1426. metadataNet.directoryID = directoryID;
  1427. metadataNet.priority = NSOperationQueuePriorityHigh;
  1428. metadataNet.selector = selectorReadFolder;
  1429. metadataNet.serverUrl = serverUrl;
  1430. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1431. }
  1432. }
  1433. #pragma mark -
  1434. #pragma --------------------------------------------------------------------------------------------
  1435. #pragma mark ===== Search =====
  1436. #pragma --------------------------------------------------------------------------------------------
  1437. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1438. {
  1439. _isSearchMode = YES;
  1440. [self deleteRefreshControl];
  1441. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1442. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1443. _searchFileName = fileName;
  1444. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12 && ![_depth isEqualToString:@"0"]) {
  1445. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:_depth delegate:self];
  1446. _noFilesSearchTitle = @"";
  1447. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1448. [self.tableView reloadEmptyDataSet];
  1449. } else {
  1450. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1451. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID == %@ AND account == %@ AND fileNamePrint CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1452. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:predicate sorted:nil ascending:NO];
  1453. [_searchResultMetadatas removeAllObjects];
  1454. for (tableMetadata *record in records)
  1455. [_searchResultMetadatas addObject:record];
  1456. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1457. metadataNet.account = app.activeAccount;
  1458. metadataNet.action = actionUploadTemplate;
  1459. metadataNet.directoryID = directoryID;
  1460. metadataNet.selector = selectorSearch;
  1461. metadataNet.serverUrl = _serverUrl;
  1462. [self readFolderSuccess:metadataNet permissions:@"" fileID:@"" metadatas:_searchResultMetadatas];
  1463. }
  1464. }
  1465. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1466. [self reloadDatasource];
  1467. }
  1468. }
  1469. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1470. {
  1471. [self cancelSearchBar];
  1472. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1473. }
  1474. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1475. {
  1476. _searchFileName = @"";
  1477. if (message)
  1478. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1479. }
  1480. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1481. {
  1482. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1483. [self readFolderSuccess:metadataNet permissions:nil fileID:nil metadatas:metadatas];
  1484. }
  1485. - (void)cancelSearchBar
  1486. {
  1487. if (self.searchController.active) {
  1488. [self.searchController setActive:NO];
  1489. [self createRefreshControl];
  1490. _isSearchMode = NO;
  1491. _searchFileName = @"";
  1492. _dateReadDataSource = nil;
  1493. _searchResultMetadatas = [NSMutableArray new];
  1494. [self reloadDatasource];
  1495. }
  1496. }
  1497. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  1498. {
  1499. NSString *title = [self.searchController.searchBar.scopeButtonTitles objectAtIndex:selectedScope];
  1500. self.searchController.searchBar.placeholder = title;
  1501. if ([title isEqualToString:NSLocalizedString(@"_search_this_folder_",nil)])
  1502. _depth = @"0";
  1503. if ([title isEqualToString:NSLocalizedString(@"_search_sub_folder_",nil)])
  1504. _depth = @"1";
  1505. if ([title isEqualToString:NSLocalizedString(@"_search_all_folders_",nil)])
  1506. _depth = @"infinity";
  1507. _searchFileName = @"";
  1508. [self updateSearchResultsForSearchController:self.searchController];
  1509. }
  1510. #pragma mark -
  1511. #pragma --------------------------------------------------------------------------------------------
  1512. #pragma mark ===== Delete File or Folder =====
  1513. #pragma --------------------------------------------------------------------------------------------
  1514. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1515. {
  1516. [self deleteFileOrFolderSuccess:metadataNet];
  1517. }
  1518. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1519. {
  1520. [_queueSelector removeObject:metadataNet.selector];
  1521. if ([_queueSelector count] == 0) {
  1522. [_hud hideHud];
  1523. if (_isSearchMode)
  1524. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1525. else
  1526. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1527. // next
  1528. if ([_selectedMetadatas count] > 0) {
  1529. [_selectedMetadatas removeObjectAtIndex:0];
  1530. if ([_selectedMetadatas count] > 0)
  1531. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1532. }
  1533. }
  1534. }
  1535. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1536. {
  1537. if (metadata.cryptated) {
  1538. [_queueSelector addObject:selectorDeleteCrypto];
  1539. [_queueSelector addObject:selectorDeletePlist];
  1540. } else {
  1541. [_queueSelector addObject:selectorDelete];
  1542. }
  1543. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1544. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1545. }
  1546. - (void)deleteSelectionFile
  1547. {
  1548. [_selectedMetadatas removeAllObjects];
  1549. [_queueSelector removeAllObjects];
  1550. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1551. _numSelectedMetadatas = [_selectedMetadatas count];
  1552. if ([_selectedMetadatas count] > 0)
  1553. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1554. [self tableViewSelect:NO];
  1555. }
  1556. - (void)deleteFile
  1557. {
  1558. [_selectedMetadatas removeAllObjects];
  1559. [_queueSelector removeAllObjects];
  1560. _numSelectedMetadatas = 1;
  1561. [_selectedMetadatas addObject:_metadata];
  1562. if ([_selectedMetadatas count] > 0)
  1563. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1564. [self tableViewSelect:NO];
  1565. }
  1566. #pragma --------------------------------------------------------------------------------------------
  1567. #pragma mark ===== Rename / Move =====
  1568. #pragma --------------------------------------------------------------------------------------------
  1569. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1570. {
  1571. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1572. }
  1573. - (void)renameFile:(tableMetadata *)metadata fileName:(NSString *)fileName
  1574. {
  1575. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1576. }
  1577. - (void)renameNote:(tableMetadata *)metadata fileName:(NSString *)fileName
  1578. {
  1579. CCTemplates *templates = [[CCTemplates alloc] init];
  1580. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1581. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1582. if (fileNameModel) {
  1583. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1584. metadataNet.action = actionUploadTemplate;
  1585. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1586. metadataNet.fileNamePrint = fileName;
  1587. metadataNet.rev = metadata.rev;
  1588. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1589. metadataNet.session = k_upload_session_foreground;
  1590. metadataNet.taskStatus = k_taskStatusResume;
  1591. if ([CCCoreData isOfflineLocalEtag:metadata.fileID activeAccount:app.activeAccount])
  1592. metadataNet.selectorPost = selectorAddOffline;
  1593. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1594. }
  1595. }
  1596. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1597. {
  1598. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1599. [_hud hideHud];
  1600. if (message)
  1601. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1602. [_selectedMetadatas removeAllObjects];
  1603. [_queueSelector removeAllObjects];
  1604. }
  1605. }
  1606. - (void)moveSuccess:(CCMetadataNet *)metadataNet revTo:(NSString *)revTo
  1607. {
  1608. [_queueSelector removeObject:metadataNet.selector];
  1609. if ([_queueSelector count] == 0) {
  1610. [_hud hideHud];
  1611. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1612. NSString *directoryID = metadataNet.directoryID;
  1613. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1614. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1615. // FILE -> Metadata
  1616. if (metadataNet.directory == NO) {
  1617. // move metadata
  1618. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1619. [[NCManageDatabase sharedInstance] moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1620. }
  1621. // DIRECTORY -> Directory - CCMetadata
  1622. if (metadataNet.directory == YES) {
  1623. // delete all dir / subdir
  1624. NSArray *directoryIDs = [CCCoreData deleteDirectoryAndSubDirectory:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName] activeAccount:app.activeAccount];
  1625. // delete all metadata and local file in dir / subdir
  1626. for (NSString *directoryIDDelete in directoryIDs) {
  1627. //[CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1628. [[NCManageDatabase sharedInstance] deleteMetadata:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1629. }
  1630. // move metadata
  1631. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1632. [[NCManageDatabase sharedInstance] moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1633. // Add new directory
  1634. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1635. NSString *directoryID = [[NCManageDatabase sharedInstance] addDirectory:newDirectory permissions:@""];
  1636. // Check Offline
  1637. if ([CCCoreData isOfflineDirectoryServerUrl:serverUrlTo activeAccount:app.activeAccount])
  1638. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1639. }
  1640. // reload Datasource
  1641. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1642. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1643. else
  1644. [self reloadDatasource];
  1645. // Next file
  1646. [_selectedMetadatas removeObjectAtIndex:0];
  1647. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:metadataNet.serverUrlTo waitUntilDone:NO];
  1648. }
  1649. }
  1650. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1651. {
  1652. if ([_selectedMetadatas count] > 0) {
  1653. tableMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1654. // Plain
  1655. if (metadata.cryptated == NO) {
  1656. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1657. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1658. if(!error) {
  1659. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1660. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1661. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1662. }];
  1663. [alert addAction:ok];
  1664. [self presentViewController:alert animated:YES completion:nil];
  1665. });
  1666. return;
  1667. }
  1668. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1669. metadataNet.action = actionMoveFileOrFolder;
  1670. metadataNet.directory = metadata.directory;
  1671. metadataNet.fileID = metadata.fileID;
  1672. metadataNet.directoryID = metadata.directoryID;
  1673. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1674. metadataNet.fileName = metadata.fileName;
  1675. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1676. metadataNet.fileNameTo = metadata.fileName;
  1677. metadataNet.rev = metadata.rev;
  1678. metadataNet.selector = selectorMove;
  1679. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1680. metadataNet.serverUrlTo = serverUrlTo;
  1681. [_queueSelector addObject:metadataNet.selector];
  1682. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1683. }
  1684. // cyptated
  1685. if (metadata.cryptated == YES) {
  1686. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1687. metadataNet.action = actionMoveFileOrFolder;
  1688. metadataNet.directory = metadata.directory;
  1689. metadataNet.fileID = metadata.fileID;
  1690. metadataNet.directoryID = metadata.directoryID;
  1691. metadataNet.directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1692. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1693. metadataNet.rev = metadata.rev;
  1694. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1695. metadataNet.serverUrlTo = serverUrlTo;
  1696. // data
  1697. metadataNet.fileName = metadata.fileNameData;
  1698. metadataNet.fileNameTo = metadata.fileNameData;
  1699. metadataNet.selector = selectorMoveCrypto;
  1700. [_queueSelector addObject:metadataNet.selector];
  1701. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1702. // plist
  1703. metadataNet.fileName = metadata.fileName;
  1704. metadataNet.fileNameTo = metadata.fileName;
  1705. metadataNet.selector = selectorMovePlist;
  1706. [_queueSelector addObject:metadataNet.selector];
  1707. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1708. }
  1709. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1710. }
  1711. }
  1712. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1713. {
  1714. [_selectedMetadatas removeAllObjects];
  1715. [_queueSelector removeAllObjects];
  1716. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1717. _numSelectedMetadatas = [_selectedMetadatas count];
  1718. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:serverUrlTo waitUntilDone:NO];
  1719. [self tableViewSelect:NO];
  1720. }
  1721. - (void)moveOpenWindow:(NSArray *)indexPaths
  1722. {
  1723. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1724. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1725. viewController.delegate = self;
  1726. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1727. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1728. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1729. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1730. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1731. viewController.networkingOperationQueue = app.netQueue;
  1732. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1733. [self presentViewController:navigationController animated:YES completion:nil];
  1734. }
  1735. #pragma --------------------------------------------------------------------------------------------
  1736. #pragma mark ===== Create folder =====
  1737. #pragma --------------------------------------------------------------------------------------------
  1738. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1739. {
  1740. [_hud hideHud];
  1741. if (message)
  1742. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1743. }
  1744. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1745. {
  1746. [_hud hideHud];
  1747. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1748. (void)[[NCManageDatabase sharedInstance] addDirectory:newDirectory permissions:@""];
  1749. // Check Offline
  1750. if ([CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount])
  1751. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1752. // Load Folder or the Datasource
  1753. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1754. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1755. } else {
  1756. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1757. }
  1758. }
  1759. - (void)createFolder:(NSString *)fileNameFolder folderCameraUpload:(BOOL)folderCameraUpload
  1760. {
  1761. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1762. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1763. if (![fileNameFolder length]) return;
  1764. if (folderCameraUpload) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPath:app.activeUrl];
  1765. else metadataNet.serverUrl = _serverUrl;
  1766. metadataNet.action = actionCreateFolder;
  1767. if (folderCameraUpload)
  1768. metadataNet.options = @"folderCameraUpload";
  1769. metadataNet.fileName = fileNameFolder;
  1770. metadataNet.selector = selectorCreateFolder;
  1771. metadataNet.selectorPost = selectorReadFolderForced;
  1772. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1773. if (!folderCameraUpload)
  1774. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1775. }
  1776. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1777. {
  1778. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1779. NSString *fileNamePlist;
  1780. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1781. if (![fileNameFolder length]) return;
  1782. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1783. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1784. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1785. // Create folder
  1786. metadataNet.action = actionCreateFolder;
  1787. metadataNet.fileName = fileNamePlist;
  1788. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1789. metadataNet.selector = selectorCreateFolder;
  1790. metadataNet.serverUrl = _serverUrl;
  1791. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1792. // upload plist file
  1793. metadataNet.action = actionUploadOnlyPlist;
  1794. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1795. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1796. metadataNet.selectorPost = selectorReadFolderForced;
  1797. metadataNet.serverUrl = _serverUrl;
  1798. metadataNet.session = k_upload_session_foreground;
  1799. metadataNet.taskStatus = k_taskStatusResume;
  1800. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1801. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1802. }
  1803. - (void)createFolderCameraUpload
  1804. {
  1805. NSString *cameraFolderName = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderName];
  1806. [self createFolder:cameraFolderName folderCameraUpload:YES];
  1807. }
  1808. #pragma --------------------------------------------------------------------------------------------
  1809. #pragma mark ===== Encrypted / Decrypted Folder =====
  1810. #pragma --------------------------------------------------------------------------------------------
  1811. - (void)encyptedDecryptedFolder
  1812. {
  1813. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1814. if (_metadata.cryptated) {
  1815. // DECRYPTED
  1816. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1817. //-------------------------- RENAME -------------------------------------------//
  1818. metadataNet.action = actionMoveFileOrFolder;
  1819. metadataNet.fileID = _metadata.fileID;
  1820. metadataNet.fileName = _metadata.fileNameData;
  1821. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1822. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1823. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1824. metadataNet.selector = selectorRename;
  1825. metadataNet.serverUrl = serverUrl;
  1826. metadataNet.serverUrlTo = serverUrl;
  1827. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1828. //-------------------------- DELETE -------------------------------------------//
  1829. metadataNet.action = actionDeleteFileDirectory;
  1830. metadataNet.fileID = _metadata.fileID;
  1831. metadataNet.fileName = _metadata.fileName;
  1832. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1833. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1834. metadataNet.selector = selectorDeletePlist;
  1835. metadataNet.selectorPost = selectorReadFolderForced;
  1836. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1837. } else {
  1838. // ENCRYPTED
  1839. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1840. // Create File Plist
  1841. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1842. //-------------------------- RENAME -------------------------------------------//
  1843. metadataNet.action = actionMoveFileOrFolder;
  1844. metadataNet.fileID = _metadata.fileID;
  1845. metadataNet.fileName = _metadata.fileName;
  1846. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1847. metadataNet.fileNameTo = fileNameCrypto;
  1848. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1849. metadataNet.selector = selectorRename;
  1850. metadataNet.serverUrl = serverUrl;
  1851. metadataNet.serverUrlTo = serverUrl;
  1852. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1853. //-------------------------- UPLOAD -------------------------------------------//
  1854. metadataNet.action = actionUploadOnlyPlist;
  1855. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1856. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1857. metadataNet.selectorPost = selectorReadFolderForced;
  1858. metadataNet.serverUrl = serverUrl;
  1859. metadataNet.session = k_upload_session_foreground;
  1860. metadataNet.taskStatus = k_taskStatusResume;
  1861. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1862. }
  1863. }
  1864. #pragma --------------------------------------------------------------------------------------------
  1865. #pragma mark ===== Encrypted/Decrypted File =====
  1866. #pragma --------------------------------------------------------------------------------------------
  1867. - (void)encryptedSelectedFiles
  1868. {
  1869. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1870. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1871. for (tableMetadata *metadata in selectedMetadatas) {
  1872. if (metadata.cryptated == NO && metadata.directory == NO)
  1873. [metadatas addObject:metadata];
  1874. }
  1875. if ([metadatas count] > 0) {
  1876. NSLog(@"[LOG] Start encrypted selected files ...");
  1877. for (tableMetadata* metadata in metadatas) {
  1878. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1879. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1880. }
  1881. }
  1882. [self tableViewSelect:NO];
  1883. }
  1884. - (void)decryptedSelectedFiles
  1885. {
  1886. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1887. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1888. for (tableMetadata *metadata in selectedMetadatas) {
  1889. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1890. [metadatas addObject:metadata];
  1891. }
  1892. if ([metadatas count] > 0) {
  1893. NSLog(@"[LOG] Start decrypted selected files ...");
  1894. for (tableMetadata* metadata in metadatas) {
  1895. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1896. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1897. }
  1898. }
  1899. [self tableViewSelect:NO];
  1900. }
  1901. - (void)cmdEncryptedDecryptedFile
  1902. {
  1903. NSString *selector;
  1904. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1905. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1906. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  1907. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1908. }
  1909. - (void)encryptedFile:(tableMetadata *)metadata
  1910. {
  1911. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1912. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1913. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1914. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1915. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1916. dispatch_async(dispatch_get_main_queue(), ^{
  1917. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1918. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1919. });
  1920. } else {
  1921. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1922. }
  1923. }
  1924. - (void)decryptedFile:(tableMetadata *)metadata
  1925. {
  1926. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1927. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1928. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1929. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1930. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1931. dispatch_async(dispatch_get_main_queue(), ^{
  1932. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1933. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1934. });
  1935. } else {
  1936. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1937. }
  1938. }
  1939. #pragma --------------------------------------------------------------------------------------------
  1940. #pragma mark ===== Progress & Task Button =====
  1941. #pragma --------------------------------------------------------------------------------------------
  1942. - (void)triggerProgressTask:(NSNotification *)notification
  1943. {
  1944. NSDictionary *dict = notification.userInfo;
  1945. NSString *fileID = [dict valueForKey:@"fileID"];
  1946. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1947. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1948. float progress = [[dict valueForKey:@"progress"] floatValue];
  1949. // Check
  1950. if (!fileID)
  1951. return;
  1952. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1953. if (![serverUrl isEqualToString:_serverUrl])
  1954. return;
  1955. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1956. if (indexPath) {
  1957. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1958. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1959. else cell.progressView.progressTintColor = [UIColor blackColor];
  1960. cell.progressView.hidden = NO;
  1961. [cell.progressView setProgress:progress];
  1962. }
  1963. if (progress == 0)
  1964. [self.navigationController cancelCCProgress];
  1965. else
  1966. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1967. }
  1968. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1969. {
  1970. UITouch * touch = [[event allTouches] anyObject];
  1971. CGPoint location = [touch locationInView:self.tableView];
  1972. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1973. if (indexPath) {
  1974. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1975. if (metadata)
  1976. [self reloadTaskButton:metadata];
  1977. }
  1978. }
  1979. - (void)reloadTaskButton:(tableMetadata *)metadata
  1980. {
  1981. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1982. __block NSURLSessionTask *findTask;
  1983. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1984. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  1985. NSString *fileID = metadata.fileID;
  1986. // DOWNLOAD
  1987. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1988. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1989. for (NSURLSessionUploadTask *task in downloadTasks)
  1990. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  1991. findTask = task;
  1992. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1993. [task cancel];
  1994. }
  1995. if (!findTask) {
  1996. dispatch_async(dispatch_get_main_queue(), ^{
  1997. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1998. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1999. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2000. });
  2001. }
  2002. }];
  2003. }
  2004. // UPLOAD
  2005. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2006. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2007. for (NSURLSessionUploadTask *task in uploadTasks)
  2008. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2009. findTask = task;
  2010. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2011. [task cancel];
  2012. }
  2013. if (!findTask) {
  2014. dispatch_async(dispatch_get_main_queue(), ^{
  2015. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2016. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2017. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2018. });
  2019. }
  2020. }];
  2021. }
  2022. }
  2023. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2024. {
  2025. UITouch * touch = [[event allTouches] anyObject];
  2026. CGPoint location = [touch locationInView:self.tableView];
  2027. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2028. if (indexPath) {
  2029. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2030. if (metadata)
  2031. [self cancelTaskButton:metadata reloadTable:YES];
  2032. }
  2033. }
  2034. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2035. {
  2036. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2037. __block NSURLSessionTask *findTask;
  2038. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2039. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2040. NSString *fileID = metadata.fileID;
  2041. // DOWNLOAD
  2042. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2043. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2044. for (NSURLSessionTask *task in downloadTasks)
  2045. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2046. findTask = task;
  2047. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2048. [task cancel];
  2049. }
  2050. if (!findTask) {
  2051. dispatch_async(dispatch_get_main_queue(), ^{
  2052. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2053. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2054. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2055. });
  2056. }
  2057. }];
  2058. }
  2059. // UPLOAD
  2060. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2061. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2062. for (NSURLSessionUploadTask *task in uploadTasks)
  2063. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2064. findTask = task;
  2065. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2066. [task cancel];
  2067. }
  2068. if (!findTask) {
  2069. dispatch_async(dispatch_get_main_queue(), ^{
  2070. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2071. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2072. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2073. });
  2074. }
  2075. }];
  2076. }
  2077. }
  2078. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2079. {
  2080. UITouch * touch = [[event allTouches] anyObject];
  2081. CGPoint location = [touch locationInView:self.tableView];
  2082. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2083. if (indexPath) {
  2084. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2085. if (metadata)
  2086. [self stopTaskButton:metadata];
  2087. }
  2088. }
  2089. - (void)stopTaskButton:(tableMetadata *)metadata
  2090. {
  2091. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2092. __block NSURLSessionTask *findTask;
  2093. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2094. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2095. NSString *fileID = metadata.fileID;
  2096. // UPLOAD
  2097. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2098. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2099. for (NSURLSessionUploadTask *task in uploadTasks)
  2100. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2101. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2102. findTask = task;
  2103. [task cancel];
  2104. }
  2105. if (!findTask) {
  2106. dispatch_async(dispatch_get_main_queue(), ^{
  2107. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2108. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2109. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2110. });
  2111. }
  2112. }];
  2113. }
  2114. }
  2115. #pragma --------------------------------------------------------------------------------------------
  2116. #pragma mark ===== Shared =====
  2117. #pragma --------------------------------------------------------------------------------------------
  2118. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2119. {
  2120. [_hud hideHud];
  2121. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2122. // change account ?
  2123. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2124. if([record.account isEqualToString:metadataNet.account] == NO)
  2125. return;
  2126. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2127. if (result) {
  2128. appDelegate.sharesLink = result[0];
  2129. appDelegate.sharesUserAndGroup = result[1];
  2130. }
  2131. if (openWindow) {
  2132. if (_shareOC) {
  2133. [_shareOC reloadData];
  2134. } else {
  2135. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2136. // Apriamo la view
  2137. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2138. _shareOC.delegate = self;
  2139. _shareOC.metadata = metadata;
  2140. _shareOC.serverUrl = metadataNet.serverUrl;
  2141. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2142. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2143. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2144. [self presentViewController:_shareOC animated:YES completion:nil];
  2145. }
  2146. }
  2147. [self tableViewReload];
  2148. }
  2149. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2150. {
  2151. [_hud hideHud];
  2152. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2153. if (_shareOC)
  2154. [_shareOC reloadData];
  2155. [self tableViewReload];
  2156. if (errorCode == 401)
  2157. [self changePasswordAccount];
  2158. }
  2159. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2160. {
  2161. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2162. metadataNet.action = actionShare;
  2163. metadataNet.fileID = metadata.fileID;
  2164. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2165. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2166. metadataNet.password = password;
  2167. metadataNet.selector = selectorShare;
  2168. metadataNet.serverUrl = serverUrl;
  2169. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2170. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2171. }
  2172. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2173. {
  2174. [_hud hideHud];
  2175. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2176. // rimuoviamo la condivisione da db
  2177. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2178. if (result) {
  2179. appDelegate.sharesLink = result[0];
  2180. appDelegate.sharesUserAndGroup = result[1];
  2181. }
  2182. if (_shareOC)
  2183. [_shareOC reloadData];
  2184. [self tableViewReload];
  2185. }
  2186. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2187. {
  2188. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2189. metadataNet.action = actionUnShare;
  2190. metadataNet.fileID = metadata.fileID;
  2191. metadataNet.fileName = metadata.fileName;
  2192. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2193. metadataNet.selector = selectorUnshare;
  2194. metadataNet.serverUrl = serverUrl;
  2195. metadataNet.share = share;
  2196. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2197. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2198. }
  2199. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2200. {
  2201. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2202. metadataNet.action = actionUpdateShare;
  2203. metadataNet.fileID = metadata.fileID;
  2204. metadataNet.expirationTime = expirationTime;
  2205. metadataNet.password = password;
  2206. metadataNet.selector = selectorUpdateShare;
  2207. metadataNet.serverUrl = serverUrl;
  2208. metadataNet.share = share;
  2209. metadataNet.sharePermission = permission;
  2210. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2211. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2212. }
  2213. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2214. {
  2215. [_hud hideHud];
  2216. if (_shareOC)
  2217. [_shareOC reloadUserAndGroup:items];
  2218. }
  2219. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2220. {
  2221. [_hud hideHud];
  2222. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2223. }
  2224. - (void)getUserAndGroup:(NSString *)find
  2225. {
  2226. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2227. metadataNet.action = actionGetUserAndGroup;
  2228. metadataNet.options = find;
  2229. metadataNet.selector = selectorGetUserAndGroup;
  2230. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2231. [_hud visibleIndeterminateHud];
  2232. }
  2233. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2234. {
  2235. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2236. metadataNet.action = actionShareWith;
  2237. metadataNet.fileID = metadata.fileID;
  2238. metadataNet.directoryID = directoryID;
  2239. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2240. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2241. metadataNet.serverUrl = serverUrl;
  2242. metadataNet.selector = selectorShare;
  2243. metadataNet.share = user;
  2244. metadataNet.shareeType = shareeType;
  2245. metadataNet.sharePermission = permission;
  2246. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2247. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2248. }
  2249. - (void)openWindowShare:(tableMetadata *)metadata
  2250. {
  2251. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2252. metadataNet.action = actionReadShareServer;
  2253. metadataNet.fileID = metadata.fileID;
  2254. metadataNet.fileName = metadata.fileName;
  2255. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2256. metadataNet.selector = selectorOpenWindowShare;
  2257. metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2258. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2259. [_hud visibleIndeterminateHud];
  2260. }
  2261. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2262. {
  2263. CGPoint location = [tapGesture locationInView:self.tableView];
  2264. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2265. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2266. if (metadata)
  2267. [self openWindowShare:metadata];
  2268. }
  2269. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2270. {
  2271. CGPoint location = [tapGesture locationInView:self.tableView];
  2272. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2273. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2274. if (metadata) {
  2275. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2276. vc.metadata = metadata;
  2277. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2278. [self presentViewController:vc animated:YES completion:nil];
  2279. }
  2280. }
  2281. #pragma --------------------------------------------------------------------------------------------
  2282. #pragma mark ===== Favorite =====
  2283. #pragma --------------------------------------------------------------------------------------------
  2284. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2285. {
  2286. _dateReadDataSource = nil;
  2287. [[NCManageDatabase sharedInstance] setMetadataFavorite:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2288. if (_isSearchMode)
  2289. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2290. else
  2291. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2292. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2293. if (metadata.directory && metadata.favorite) {
  2294. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2295. [[CCSynchronize sharedSynchronize] addFavoriteFolder:dir];
  2296. }
  2297. }
  2298. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2299. {
  2300. }
  2301. - (void)addFavorite:(tableMetadata *)metadata
  2302. {
  2303. if (metadata.directory) {
  2304. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2305. } else {
  2306. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2307. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2308. }
  2309. }
  2310. - (void)removeFavorite:(tableMetadata *)metadata
  2311. {
  2312. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2313. }
  2314. #pragma --------------------------------------------------------------------------------------------
  2315. #pragma mark ===== Offline =====
  2316. #pragma --------------------------------------------------------------------------------------------
  2317. - (void)addOffline:(tableMetadata *)metadata
  2318. {
  2319. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2320. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddOffline selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2321. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2322. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2323. }
  2324. - (void)removeOffline:(tableMetadata *)metadata
  2325. {
  2326. [CCCoreData setOfflineLocalEtag:metadata.fileID offline:NO activeAccount:app.activeAccount];
  2327. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2328. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2329. }
  2330. #pragma --------------------------------------------------------------------------------------------
  2331. #pragma mark ===== Local =====
  2332. #pragma --------------------------------------------------------------------------------------------
  2333. - (void)addLocal:(tableMetadata *)metadata
  2334. {
  2335. if (metadata.errorPasscode || !metadata.uuid) return;
  2336. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2337. if ([metadata.type isEqualToString: k_metadataType_file])
  2338. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2339. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2340. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2341. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2342. }
  2343. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2344. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2345. }
  2346. #pragma --------------------------------------------------------------------------------------------
  2347. #pragma mark ===== Open in... =====
  2348. #pragma --------------------------------------------------------------------------------------------
  2349. - (void)openIn:(tableMetadata *)metadata
  2350. {
  2351. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2352. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2353. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2354. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2355. }
  2356. #pragma --------------------------------------------------------------------------------------------
  2357. #pragma mark ===== Remove Local File =====
  2358. #pragma --------------------------------------------------------------------------------------------
  2359. - (void)removeLocalFile:(tableMetadata *)metadata
  2360. {
  2361. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2362. [CCCoreData deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileID == %@)", app.activeAccount, metadata.fileID]];
  2363. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2364. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:nil];
  2365. }
  2366. #pragma --------------------------------------------------------------------------------------------
  2367. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2368. #pragma --------------------------------------------------------------------------------------------
  2369. - (void)orderTable:(NSString *)order
  2370. {
  2371. [CCUtility setOrderSettings:order];
  2372. // Clear data-read of DataSource
  2373. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2374. }
  2375. - (void)ascendingTable:(BOOL)ascending
  2376. {
  2377. [CCUtility setAscendingSettings:ascending];
  2378. // Clear data-read of DataSource
  2379. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2380. }
  2381. - (void)directoryOnTop:(BOOL)directoryOnTop
  2382. {
  2383. [CCUtility setDirectoryOnTop:directoryOnTop];
  2384. // Clear data-read of DataSource
  2385. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2386. }
  2387. - (void)tableGroupBy:(NSString *)groupBy
  2388. {
  2389. [CCUtility setGroupBySettings:groupBy];
  2390. // Clear data-read of DataSource
  2391. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2392. }
  2393. #pragma --------------------------------------------------------------------------------------------
  2394. #pragma mark ==== Menu LOGO ====
  2395. #pragma --------------------------------------------------------------------------------------------
  2396. - (void)menuLogo
  2397. {
  2398. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2399. return;
  2400. // Brand
  2401. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2402. return;
  2403. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [[NCManageDatabase sharedInstance] countAutomaticUpload:nil] > 0) {
  2404. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2405. return;
  2406. }
  2407. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2408. NSMutableArray *menuArray = [NSMutableArray new];
  2409. for (NSString *account in listAccount) {
  2410. if ([account isEqualToString:app.activeAccount]) continue;
  2411. CCMenuItem *item = [[CCMenuItem alloc] init];
  2412. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2413. item.argument = account;
  2414. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2415. item.target = self;
  2416. item.action = @selector(changeDefaultAccount:);
  2417. [menuArray addObject:item];
  2418. }
  2419. if ([menuArray count] == 0)
  2420. return;
  2421. OptionalConfiguration options;
  2422. Color textColor, backgroundColor;
  2423. textColor.R = 0;
  2424. textColor.G = 0;
  2425. textColor.B = 0;
  2426. backgroundColor.R = 1;
  2427. backgroundColor.G = 1;
  2428. backgroundColor.B = 1;
  2429. NSInteger originY = 60;
  2430. options.arrowSize = 9;
  2431. options.marginXSpacing = 7;
  2432. options.marginYSpacing = 10;
  2433. options.intervalSpacing = 20;
  2434. options.menuCornerRadius = 6.5;
  2435. options.maskToBackground = NO;
  2436. options.shadowOfMenu = YES;
  2437. options.hasSeperatorLine = YES;
  2438. options.seperatorLineHasInsets = YES;
  2439. options.textColor = textColor;
  2440. options.menuBackgroundColor = backgroundColor;
  2441. CGRect rect = self.view.frame;
  2442. rect.origin.y = rect.origin.y + originY;
  2443. rect.size.height = rect.size.height - originY;
  2444. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2445. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2446. }
  2447. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2448. {
  2449. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2450. // STOP, erase all in queue networking
  2451. [app cancelAllOperations];
  2452. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2453. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2454. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2455. if (tableAccount)
  2456. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2457. // go to home sweet home
  2458. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2459. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2460. });
  2461. }
  2462. #pragma --------------------------------------------------------------------------------------------
  2463. #pragma mark ==== ReMenu ====
  2464. #pragma --------------------------------------------------------------------------------------------
  2465. - (void)createReMenuBackgroundView:(REMenu *)menu
  2466. {
  2467. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2468. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2469. [UIView animateWithDuration:0.2 animations:^{
  2470. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2471. if (height < self.tabBarController.tabBar.frame.size.height)
  2472. height = self.tabBarController.tabBar.frame.size.height;
  2473. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2474. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2475. }];
  2476. }
  2477. - (void)createReMainMenu
  2478. {
  2479. NSString *ordinamento;
  2480. NSString *groupBy = _directoryGroupBy;
  2481. __block NSString *nuovoOrdinamento;
  2482. NSString *titoloNuovo, *titoloAttuale;
  2483. BOOL ascendente;
  2484. __block BOOL nuovoAscendente;
  2485. UIImage *image;
  2486. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2487. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2488. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2489. [self tableViewSelect:YES];
  2490. }
  2491. }];
  2492. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2493. ordinamento = _directoryOrder;
  2494. if ([ordinamento isEqualToString:@"fileName"]) {
  2495. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2496. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2497. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2498. nuovoOrdinamento = @"fileDate";
  2499. }
  2500. if ([ordinamento isEqualToString:@"fileDate"]) {
  2501. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2502. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2503. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2504. nuovoOrdinamento = @"fileName";
  2505. }
  2506. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2507. [self orderTable:nuovoOrdinamento];
  2508. }];
  2509. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2510. ascendente = [CCUtility getAscendingSettings];
  2511. if (ascendente) {
  2512. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2513. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2514. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2515. nuovoAscendente = false;
  2516. }
  2517. if (!ascendente) {
  2518. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2519. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2520. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2521. nuovoAscendente = true;
  2522. }
  2523. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2524. [self ascendingTable:nuovoAscendente];
  2525. }];
  2526. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2527. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2528. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2529. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2530. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2531. else [self tableGroupBy:@"alphabetic"];
  2532. }];
  2533. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2534. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2535. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2536. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2537. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2538. else [self tableGroupBy:@"typefile"];
  2539. }];
  2540. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2541. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2542. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2543. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2544. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2545. else [self tableGroupBy:@"date"];
  2546. }];
  2547. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2548. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2549. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2550. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2551. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2552. else [self directoryOnTop:YES];
  2553. }];
  2554. // REMENU --------------------------------------------------------------------------------------------------------------
  2555. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2556. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2557. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2558. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2559. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2560. app.reMainMenu.separatorHeight = 0.5;
  2561. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2562. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2563. app.reMainMenu.textColor = [UIColor blackColor];
  2564. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2565. app.reMainMenu.textShadowColor = nil;
  2566. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2567. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2568. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2569. app.reMainMenu.highlightedSeparatorColor = nil;
  2570. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2571. app.reMainMenu.highlightedTextShadowColor = nil;
  2572. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2573. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2574. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2575. app.reMainMenu.subtitleTextShadowColor = nil;
  2576. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2577. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2578. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2579. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2580. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2581. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2582. app.reMainMenu.borderWidth = 0.3;
  2583. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2584. app.reMainMenu.animationDuration = 0.2;
  2585. app.reMainMenu.closeAnimationDuration = 0.2;
  2586. app.reMainMenu.bounce = NO;
  2587. [app.reMainMenu setClosePreparationBlock:^{
  2588. // Backgroun reMenu (Gesture)
  2589. [_reMenuBackgroundView removeFromSuperview];
  2590. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2591. }];
  2592. }
  2593. - (void)toggleReMainMenu
  2594. {
  2595. if (app.reMainMenu.isOpen) {
  2596. [app.reMainMenu close];
  2597. } else {
  2598. [self createReMainMenu];
  2599. [app.reMainMenu showFromNavigationController:self.navigationController];
  2600. // Backgroun reMenu & (Gesture)
  2601. [self createReMenuBackgroundView:app.reMainMenu];
  2602. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2603. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2604. }
  2605. }
  2606. - (void)createReSelectMenu
  2607. {
  2608. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2609. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2610. [self deleteSelectionFile];
  2611. }];
  2612. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2613. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2614. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2615. }];
  2616. if (app.isCryptoCloudMode) {
  2617. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2618. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2619. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2620. }];
  2621. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2622. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2623. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2624. }];
  2625. }
  2626. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2627. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2628. [self downloadSelectedFiles];
  2629. }];
  2630. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2631. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2632. [self saveSelectedFiles];
  2633. }];
  2634. // REMENU --------------------------------------------------------------------------------------------------------------
  2635. if (app.isCryptoCloudMode) {
  2636. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2637. } else {
  2638. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2639. }
  2640. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2641. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2642. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2643. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2644. app.reSelectMenu.separatorHeight = 0.5;
  2645. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2646. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2647. app.reSelectMenu.textColor = [UIColor blackColor];
  2648. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2649. app.reSelectMenu.textShadowColor = nil;
  2650. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2651. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2652. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2653. app.reSelectMenu.highlightedSeparatorColor = nil;
  2654. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2655. app.reSelectMenu.highlightedTextShadowColor = nil;
  2656. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2657. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2658. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2659. app.reSelectMenu.subtitleTextShadowColor = nil;
  2660. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2661. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2662. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2663. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2664. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2665. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2666. app.reSelectMenu.borderWidth = 0.3;
  2667. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2668. app.reSelectMenu.closeAnimationDuration = 0.2;
  2669. app.reSelectMenu.animationDuration = 0.2;
  2670. app.reSelectMenu.bounce = NO;
  2671. [app.reSelectMenu setClosePreparationBlock:^{
  2672. // Backgroun reMenu (Gesture)
  2673. [_reMenuBackgroundView removeFromSuperview];
  2674. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2675. }];
  2676. }
  2677. - (void)toggleReSelectMenu
  2678. {
  2679. if (app.reSelectMenu.isOpen) {
  2680. [app.reSelectMenu close];
  2681. } else {
  2682. [self createReSelectMenu];
  2683. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2684. // Backgroun reMenu & (Gesture)
  2685. [self createReMenuBackgroundView:app.reSelectMenu];
  2686. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2687. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2688. }
  2689. }
  2690. #pragma --------------------------------------------------------------------------------------------
  2691. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2692. #pragma --------------------------------------------------------------------------------------------
  2693. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2694. {
  2695. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2696. UITableView *tableView = (UITableView*)self.view;
  2697. CGPoint touchPoint = [recognizer locationInView:self.view];
  2698. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2699. if (indexPath)
  2700. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2701. else
  2702. _metadata = nil;
  2703. [self becomeFirstResponder];
  2704. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2705. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2706. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2707. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2708. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2709. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2710. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2711. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2712. if (app.isCryptoCloudMode)
  2713. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2714. else
  2715. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2716. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2717. [menuController setMenuVisible:YES animated:YES];
  2718. }
  2719. }
  2720. - (BOOL)canBecomeFirstResponder
  2721. {
  2722. return YES;
  2723. }
  2724. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2725. {
  2726. // For copy file, copy files, Open in ... :
  2727. //
  2728. // NO Directory
  2729. // NO Error Passcode
  2730. // NO In Session mode (download/upload)
  2731. // NO Template
  2732. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2733. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2734. // NO Cryptated with Title lenght = 0
  2735. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2736. return YES;
  2737. }
  2738. return NO;
  2739. }
  2740. if (@selector(copyFiles:) == action) {
  2741. if (_isSelectedMode) {
  2742. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2743. for (tableMetadata *metadata in selectedMetadatas) {
  2744. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2745. // NO Cryptated with Title lenght = 0
  2746. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2747. return YES;
  2748. }
  2749. }
  2750. }
  2751. return NO;
  2752. }
  2753. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2754. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2755. NSArray *items = [pasteboard items];
  2756. if ([items count] == 1) {
  2757. // Value : (NSData) fileID
  2758. NSDictionary *dic = [items objectAtIndex:0];
  2759. NSData *dataEtag = [dic objectForKey: k_metadataKeyedUnarchiver];
  2760. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataEtag];
  2761. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2762. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2763. if (directoryUser) {
  2764. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2765. return YES;
  2766. }
  2767. return NO;
  2768. } else return NO;
  2769. }
  2770. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2771. BOOL isValid = NO;
  2772. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2773. NSArray *items = [pasteboard items];
  2774. if ([items count] <= 1) return NO;
  2775. for (NSDictionary *dic in items) {
  2776. // Value : (NSData) fileID
  2777. NSData *dataEtag = [dic objectForKey: k_metadataKeyedUnarchiver];
  2778. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataEtag];
  2779. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2780. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2781. if (directoryUser) {
  2782. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2783. isValid = YES;
  2784. }
  2785. }
  2786. return isValid;
  2787. }
  2788. return NO;
  2789. }
  2790. /************************************ COPY ************************************/
  2791. - (void)copyFile:(id)sender
  2792. {
  2793. // Remove all item
  2794. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2795. pasteboard.items = [[NSArray alloc] init];
  2796. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2797. [self copyFileToPasteboard:_metadata];
  2798. } else {
  2799. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2800. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2801. }
  2802. }
  2803. - (void)copyFiles:(id)sender
  2804. {
  2805. // Remove all item
  2806. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2807. pasteboard.items = [[NSArray alloc] init];
  2808. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2809. for (tableMetadata *metadata in selectedMetadatas) {
  2810. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2811. [self copyFileToPasteboard:metadata];
  2812. } else {
  2813. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2814. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2815. }
  2816. }
  2817. [self tableViewSelect:NO];
  2818. }
  2819. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2820. {
  2821. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2822. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2823. // Value : (NSData) fileID
  2824. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2825. [items addObject:item];
  2826. [pasteboard setItems:items];
  2827. }
  2828. /************************************ OPEN IN ... ************************************/
  2829. - (void)openinFile:(id)sender
  2830. {
  2831. [self openIn:_metadata];
  2832. }
  2833. /************************************ PASTE ************************************/
  2834. - (void)pasteFile:(id)sender
  2835. {
  2836. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2837. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2838. }
  2839. - (void)pasteFileEncrypted:(id)sender
  2840. {
  2841. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2842. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2843. }
  2844. - (void)pasteFiles:(id)sender
  2845. {
  2846. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2847. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2848. }
  2849. - (void)pasteFilesEncrypted:(id)sender
  2850. {
  2851. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2852. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2853. }
  2854. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2855. {
  2856. for (NSDictionary *dic in items) {
  2857. // Value : (NSData) fileID
  2858. NSData *dataEtag = [dic objectForKey: k_metadataKeyedUnarchiver];
  2859. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataEtag];
  2860. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2861. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2862. if (!metadata || !account) return;
  2863. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2864. if (directoryUser) {
  2865. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2866. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2867. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2868. }
  2869. }
  2870. }
  2871. }
  2872. #pragma --------------------------------------------------------------------------------------------
  2873. #pragma mark ===== Lock Passcode =====
  2874. #pragma --------------------------------------------------------------------------------------------
  2875. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2876. {
  2877. return _failedAttempts;
  2878. }
  2879. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2880. {
  2881. return _lockUntilDate;
  2882. }
  2883. - (void)passcodeViewCloseButtonPressed:(id)sender
  2884. {
  2885. [self dismissViewControllerAnimated:YES completion:nil];
  2886. }
  2887. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2888. {
  2889. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2890. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2891. _lockUntilDate = nil;
  2892. _failedAttempts = 0;
  2893. aResultHandler(YES);
  2894. } else aResultHandler(NO);
  2895. } else aResultHandler(YES);
  2896. }
  2897. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2898. {
  2899. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2900. switch (aViewController.type) {
  2901. case BKPasscodeViewControllerCheckPasscodeType: {
  2902. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2903. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2904. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2905. // scriviamo il passcode
  2906. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2907. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2908. } else {
  2909. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2910. [alertView show];
  2911. }
  2912. }
  2913. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2914. // possiamo procedere alla prossima directory
  2915. [self performSegueDirectoryWithControlPasscode:false];
  2916. // avviamo la sessione Passcode Lock con now
  2917. app.sessionePasscodeLock = [NSDate date];
  2918. }
  2919. // disattivazione lock cartella
  2920. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2921. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2922. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2923. if ([CCCoreData setDirectoryUnLock:lockServerUrl activeAccount:app.activeAccount] == NO) {
  2924. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2925. }
  2926. [self.tableView reloadData];
  2927. }
  2928. }
  2929. break;
  2930. default:
  2931. break;
  2932. }
  2933. }
  2934. - (void)comandoLockPassword
  2935. {
  2936. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2937. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2938. // se non è abilitato il Lock Passcode esci
  2939. if ([[CCUtility getBlockCode] length] == 0) {
  2940. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2941. [alertView show];
  2942. return;
  2943. }
  2944. // se è richiesta la disattivazione si chiede la password
  2945. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPreficate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  2946. if (directory.lock) {
  2947. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2948. viewController.delegate = self;
  2949. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2950. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2951. viewController.inputViewTitlePassword = YES;
  2952. if ([CCUtility getSimplyBlockCode]) {
  2953. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2954. viewController.passcodeInputView.maximumLength = 6;
  2955. } else {
  2956. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2957. viewController.passcodeInputView.maximumLength = 64;
  2958. }
  2959. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2960. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2961. viewController.touchIDManager = touchIDManager;
  2962. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2963. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2964. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2965. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2966. [self presentViewController:navigationController animated:YES completion:nil];
  2967. return;
  2968. }
  2969. // ---------------- ACTIVATE PASSWORD
  2970. if([CCCoreData setDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2971. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2972. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2973. } else {
  2974. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2975. }
  2976. }
  2977. #pragma mark -
  2978. #pragma --------------------------------------------------------------------------------------------
  2979. #pragma mark ===== Swipe Tablet -> menu =====
  2980. #pragma --------------------------------------------------------------------------------------------
  2981. // more
  2982. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  2983. return NSLocalizedString(@"_more_", nil);
  2984. }
  2985. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  2986. {
  2987. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2988. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2989. NSString *titoloCriptaDecripta, *titoloOffline, *titoloLock, *titleFavorite;
  2990. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  2991. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2992. if ([CCCoreData isOfflineLocalEtag:_metadata.fileID activeAccount:app.activeAccount]) titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  2993. else titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  2994. if (_metadata.favorite) {
  2995. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2996. } else {
  2997. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2998. }
  2999. if (_metadata.directory) {
  3000. // calcolo lockServerUrl
  3001. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3002. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPreficate:[NSPredicate predicateWithFormat:@"serverUrl = %@", lockServerUrl]];
  3003. if (directory.lock)
  3004. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3005. else
  3006. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3007. }
  3008. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithEtag:_metadata.fileID activeAccount:app.activeAccount];
  3009. /******************************************* AHKActionSheet *******************************************/
  3010. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3011. actionSheet.animationDuration = 0.2;
  3012. actionSheet.blurRadius = 0.0f;
  3013. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3014. actionSheet.buttonHeight = 50.0;
  3015. actionSheet.cancelButtonHeight = 50.0f;
  3016. actionSheet.separatorHeight = 5.0f;
  3017. actionSheet.automaticallyTintButtonImages = @(NO);
  3018. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3019. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3020. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3021. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3022. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3023. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3024. /******************************************* DIRECTORY *******************************************/
  3025. if (_metadata.directory) {
  3026. BOOL lockDirectory = NO;
  3027. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3028. // Directory bloccata ?
  3029. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPreficate:[NSPredicate predicateWithFormat:@"serverUrl = %@", dirServerUrl]];
  3030. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3031. NSString *cameraUploadFolderName = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderName];
  3032. NSString *cameraUploadFolderPath = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPath:app.activeUrl];
  3033. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3034. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3035. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3036. height: 50.0
  3037. type: AHKActionSheetButtonTypeDisabled
  3038. handler: nil
  3039. ];
  3040. if (!lockDirectory && !_metadata.cryptated) {
  3041. [actionSheet addButtonWithTitle:titleFavorite
  3042. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3043. backgroundColor:[UIColor whiteColor]
  3044. height: 50.0
  3045. type:AHKActionSheetButtonTypeDefault
  3046. handler:^(AHKActionSheet *as) {
  3047. // close swipe
  3048. [self setEditing:NO animated:YES];
  3049. if (_metadata.favorite)
  3050. [self removeFavorite:_metadata];
  3051. else
  3052. [self addFavorite:_metadata];
  3053. }];
  3054. }
  3055. if (_metadata.cryptated == NO && !lockDirectory) {
  3056. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3057. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3058. backgroundColor:[UIColor whiteColor]
  3059. height: 50.0
  3060. type:AHKActionSheetButtonTypeDefault
  3061. handler:^(AHKActionSheet *as) {
  3062. // close swipe
  3063. [self setEditing:NO animated:YES];
  3064. [self openWindowShare:_metadata];
  3065. }];
  3066. }
  3067. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3068. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3069. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3070. backgroundColor:[UIColor whiteColor]
  3071. height: 50.0
  3072. type:AHKActionSheetButtonTypeDefault
  3073. handler:^(AHKActionSheet *as) {
  3074. // close swipe
  3075. [self setEditing:NO animated:YES];
  3076. //chiediamo il nome del file
  3077. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3078. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3079. alertView.tag = alertRename;
  3080. UITextField *textField = [alertView textFieldAtIndex:0];
  3081. textField.text = _metadata.fileNamePrint;
  3082. [alertView show];
  3083. }];
  3084. }
  3085. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3086. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3087. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3088. backgroundColor:[UIColor whiteColor]
  3089. height: 50.0
  3090. type:AHKActionSheetButtonTypeDefault
  3091. handler:^(AHKActionSheet *as) {
  3092. // close swipe
  3093. [self setEditing:NO animated:YES];
  3094. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3095. }];
  3096. }
  3097. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3098. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3099. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3100. backgroundColor:[UIColor whiteColor]
  3101. height: 50.0
  3102. type:AHKActionSheetButtonTypeDefault
  3103. handler:^(AHKActionSheet *as) {
  3104. // close swipe
  3105. [self setEditing:NO animated:YES];
  3106. // Settings new folder Automatatic upload
  3107. NSString *oldPath = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPath:app.activeUrl];
  3108. [[NCManageDatabase sharedInstance] setAccountCameraUploadFolderName:_metadata.fileName];
  3109. [[NCManageDatabase sharedInstance] setAccountCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl];
  3110. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:oldPath directoryID:nil];
  3111. if (app.activeAccount.length > 0 && app.activePhotosCameraUpload)
  3112. [app.activePhotosCameraUpload reloadDatasourceForced];
  3113. [self readFolderWithForced:YES serverUrl:serverUrl];
  3114. NSLog(@"[LOG] Update Folder Photo");
  3115. NSString *folderCameraUpload = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathAndName:app.activeUrl];
  3116. if ([folderCameraUpload length] > 0)
  3117. [[CCSynchronize sharedSynchronize] readFolderServerUrl:folderCameraUpload directoryID:[[NCManageDatabase sharedInstance] getDirectoryID:folderCameraUpload] selector:selectorReadFolder];
  3118. }];
  3119. }
  3120. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3121. [actionSheet addButtonWithTitle:titoloLock
  3122. image:[UIImage imageNamed:@"actionSheetLock"]
  3123. backgroundColor:[UIColor whiteColor]
  3124. height: 50.0
  3125. type:AHKActionSheetButtonTypeEncrypted
  3126. handler:^(AHKActionSheet *as) {
  3127. // close swipe
  3128. [self setEditing:NO animated:YES];
  3129. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3130. }];
  3131. }
  3132. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3133. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3134. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3135. backgroundColor:[UIColor whiteColor]
  3136. height: 50.0
  3137. type:AHKActionSheetButtonTypeEncrypted
  3138. handler:^(AHKActionSheet *as) {
  3139. // close swipe
  3140. [self setEditing:NO animated:YES];
  3141. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3142. }];
  3143. }
  3144. [actionSheet show];
  3145. }
  3146. /******************************************* FILE *******************************************/
  3147. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3148. UIImage *iconHeader;
  3149. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3150. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3151. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3152. else
  3153. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3154. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3155. image: iconHeader
  3156. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3157. height: 50.0
  3158. type: AHKActionSheetButtonTypeDisabled
  3159. handler: nil
  3160. ];
  3161. if (!_metadata.cryptated) {
  3162. [actionSheet addButtonWithTitle:titleFavorite
  3163. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3164. backgroundColor:[UIColor whiteColor]
  3165. height: 50.0
  3166. type:AHKActionSheetButtonTypeDefault
  3167. handler:^(AHKActionSheet *as) {
  3168. // close swipe
  3169. [self setEditing:NO animated:YES];
  3170. if (_metadata.favorite)
  3171. [self removeFavorite:_metadata];
  3172. else
  3173. [self addFavorite:_metadata];
  3174. }];
  3175. }
  3176. if (_metadata.cryptated == NO) {
  3177. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3178. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3179. backgroundColor:[UIColor whiteColor]
  3180. height: 50.0
  3181. type:AHKActionSheetButtonTypeDefault
  3182. handler:^(AHKActionSheet *as) {
  3183. // close swipe
  3184. [self setEditing:NO animated:YES];
  3185. [self openWindowShare:_metadata];
  3186. }];
  3187. }
  3188. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3189. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3190. backgroundColor:[UIColor whiteColor]
  3191. height: 50.0
  3192. type:AHKActionSheetButtonTypeDefault
  3193. handler:^(AHKActionSheet *as) {
  3194. // close swipe
  3195. [self setEditing:NO animated:YES];
  3196. [self performSelector:@selector(openIn:) withObject:_metadata];
  3197. }];
  3198. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3199. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3200. backgroundColor:[UIColor whiteColor]
  3201. height: 50.0
  3202. type:AHKActionSheetButtonTypeDefault
  3203. handler:^(AHKActionSheet *as) {
  3204. // close swipe
  3205. [self setEditing:NO animated:YES];
  3206. //chiediamo il nome del file
  3207. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3208. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3209. alertView.tag = alertRename;
  3210. UITextField *textField = [alertView textFieldAtIndex:0];
  3211. textField.text = _metadata.fileNamePrint;
  3212. [alertView show];
  3213. }];
  3214. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3215. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3216. backgroundColor:[UIColor whiteColor]
  3217. height: 50.0
  3218. type:AHKActionSheetButtonTypeDefault
  3219. handler:^(AHKActionSheet *as) {
  3220. // close swipe
  3221. [self setEditing:NO animated:YES];
  3222. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3223. }];
  3224. if (recordLocalFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3225. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3226. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3227. backgroundColor:[UIColor whiteColor]
  3228. height: 50.0
  3229. type:AHKActionSheetButtonTypeDefault
  3230. handler:^(AHKActionSheet *as) {
  3231. // close swipe
  3232. [self setEditing:NO animated:YES];
  3233. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3234. }];
  3235. }
  3236. if (app.isCryptoCloudMode) {
  3237. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3238. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3239. backgroundColor:[UIColor whiteColor]
  3240. height: 50.0
  3241. type:AHKActionSheetButtonTypeEncrypted
  3242. handler:^(AHKActionSheet *as) {
  3243. // close swipe
  3244. [self setEditing:NO animated:YES];
  3245. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3246. }];
  3247. }
  3248. [actionSheet show];
  3249. }
  3250. /******************************************* TEMPLATE *******************************************/
  3251. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3252. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3253. image: [UIImage imageNamed:_metadata.iconName]
  3254. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3255. height: 50.0
  3256. type: AHKActionSheetButtonTypeDisabled
  3257. handler: nil
  3258. ];
  3259. if ([_metadata.model isEqualToString:@"note"]) {
  3260. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3261. image:[UIImage imageNamed:@"actionSheetRename"]
  3262. backgroundColor:[UIColor whiteColor]
  3263. height: 50.0
  3264. type:AHKActionSheetButtonTypeDefault
  3265. handler:^(AHKActionSheet *as) {
  3266. // close swipe
  3267. [self setEditing:NO animated:YES];
  3268. //chiediamo il nome del file
  3269. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3270. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3271. alertView.tag = alertRename;
  3272. UITextField *textField = [alertView textFieldAtIndex:0];
  3273. textField.text = _metadata.fileNamePrint;
  3274. [alertView show];
  3275. }];
  3276. }
  3277. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3278. image:[UIImage imageNamed:@"actionSheetMove"]
  3279. backgroundColor:[UIColor whiteColor]
  3280. height: 50.0
  3281. type:AHKActionSheetButtonTypeDefault
  3282. handler:^(AHKActionSheet *as) {
  3283. // close swipe
  3284. [self setEditing:NO animated:YES];
  3285. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3286. }];
  3287. [actionSheet show];
  3288. }
  3289. }
  3290. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3291. {
  3292. return NSLocalizedString(@"_delete_", nil);
  3293. }
  3294. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3295. {
  3296. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3297. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3298. return NO;
  3299. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3300. else return YES;
  3301. }
  3302. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3303. {
  3304. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3305. if (_metadata.errorPasscode || (_metadata.cryptated && [_metadata.title length] == 0) || _metadata.sessionTaskIdentifier >= 0 || _metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3306. else return UITableViewCellEditingStyleDelete;
  3307. }
  3308. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3309. {
  3310. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3311. BOOL lockDirectory = NO;
  3312. // Directory locked ?
  3313. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID] addFileName:_metadata.fileNameData];
  3314. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPreficate:[NSPredicate predicateWithFormat:@"serverUrl = %@", dirServerUrl]];
  3315. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil)
  3316. lockDirectory = YES;
  3317. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3318. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3319. return;
  3320. }
  3321. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3322. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3323. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3324. style:UIAlertActionStyleDestructive
  3325. handler:^(UIAlertAction *action) {
  3326. [self performSelector:@selector(deleteFile) withObject:nil];
  3327. }]];
  3328. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3329. style:UIAlertActionStyleCancel
  3330. handler:^(UIAlertAction *action) {
  3331. [alertController dismissViewControllerAnimated:YES completion:nil];
  3332. }]];
  3333. alertController.popoverPresentationController.sourceView = self.view;
  3334. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3335. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3336. [alertController.view layoutIfNeeded];
  3337. [self presentViewController:alertController animated:YES completion:nil];
  3338. }
  3339. }
  3340. #pragma --------------------------------------------------------------------------------------------
  3341. #pragma mark - ==== Datasource ====
  3342. #pragma --------------------------------------------------------------------------------------------
  3343. - (void)clearDateReadDataSource:(NSNotification *)notification
  3344. {
  3345. _dateReadDataSource = Nil;
  3346. [self reloadDatasource];
  3347. }
  3348. - (void)reloadDatasource
  3349. {
  3350. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3351. }
  3352. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3353. {
  3354. // test
  3355. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3356. return;
  3357. // Search Mode
  3358. if(_isSearchMode) {
  3359. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3360. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3361. } else {
  3362. [self readFolderWithForced:NO serverUrl:serverUrl];
  3363. }
  3364. [self tableViewReload];
  3365. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3366. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3367. _noFilesSearchDescription = @"";
  3368. }
  3369. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3370. _noFilesSearchTitle = @"";
  3371. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3372. }
  3373. [self.tableView reloadEmptyDataSet];
  3374. return;
  3375. }
  3376. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3377. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3378. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3379. [app.activeTransfers reloadDatasource];
  3380. } else {
  3381. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3382. if (main) {
  3383. [main reloadDatasource];
  3384. } else {
  3385. [self tableViewReload];
  3386. [app.activeTransfers reloadDatasource];
  3387. }
  3388. }
  3389. return;
  3390. }
  3391. // Offline folder ?
  3392. _isOfflineServerUrl = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  3393. [app.activeTransfers reloadDatasource];
  3394. // Settaggio variabili per le ottimizzazioni
  3395. _directoryGroupBy = [CCUtility getGroupBySettings];
  3396. _directoryOrder = [CCUtility getOrderSettings];
  3397. // Controllo data lettura Data Source
  3398. NSDate *dateDateRecordDirectory = [CCCoreData getDateReadDirectoryID:[[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl] activeAccount:app.activeAccount];
  3399. dateDateRecordDirectory = nil;
  3400. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3401. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3402. _dateReadDataSource = [NSDate date];
  3403. // Data Source
  3404. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl]] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3405. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3406. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3407. } else {
  3408. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3409. }
  3410. [self tableViewReload];
  3411. }
  3412. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3413. {
  3414. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3415. if (selectedRows.count > 0) {
  3416. for (NSIndexPath *selectionIndex in selectedRows) {
  3417. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3418. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3419. [metadatas addObject:metadata];
  3420. }
  3421. }
  3422. return metadatas;
  3423. }
  3424. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3425. {
  3426. NSInteger section = indexPath.section + 1;
  3427. NSInteger row = indexPath.row + 1;
  3428. NSInteger totSections =[_sectionDataSource.sections count] ;
  3429. if ((totSections < section) || (section > totSections)) {
  3430. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3431. return nil;
  3432. }
  3433. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3434. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3435. if (fileIDs) {
  3436. NSInteger totRows =[fileIDs count] ;
  3437. if ((totRows < row) || (row > totRows)) {
  3438. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3439. return nil;
  3440. }
  3441. } else {
  3442. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3443. return nil;
  3444. }
  3445. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3446. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3447. return metadata;
  3448. }
  3449. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3450. {
  3451. NSInteger totSections =[_sectionDataSource.sections count] ;
  3452. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3453. #if DEBUG
  3454. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3455. [alertView show];
  3456. #endif
  3457. return nil;
  3458. }
  3459. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3460. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3461. }
  3462. #pragma --------------------------------------------------------------------------------------------
  3463. #pragma mark - ==== Table ====
  3464. #pragma --------------------------------------------------------------------------------------------
  3465. - (void)tableViewSelect:(BOOL)edit
  3466. {
  3467. // chiudiamo eventuali swipe aperti
  3468. if (edit) [self.tableView setEditing:NO animated:NO];
  3469. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3470. [self.tableView setEditing:edit animated:YES];
  3471. _isSelectedMode = edit;
  3472. if (edit)
  3473. [self setUINavigationBarSelected];
  3474. else
  3475. [self setUINavigationBarDefault];
  3476. [self setTitle];
  3477. }
  3478. - (void)tableViewReload
  3479. {
  3480. // ricordiamoci le row selezionate
  3481. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3482. [self.tableView reloadData];
  3483. for (NSIndexPath *path in indexPaths)
  3484. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3485. [self setTableViewFooter];
  3486. if (self.tableView.editing)
  3487. [self setTitle];
  3488. }
  3489. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3490. {
  3491. return 60;
  3492. }
  3493. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3494. {
  3495. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3496. }
  3497. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3498. {
  3499. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3500. }
  3501. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3502. {
  3503. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3504. NSString *sectionTitle = [sections objectAtIndex:section];
  3505. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3506. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3507. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3508. return 20.f;
  3509. }
  3510. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3511. {
  3512. float shift;
  3513. UIVisualEffectView *visualEffectView;
  3514. // Titolo
  3515. NSString *titleSection;
  3516. // Controllo
  3517. if ([_sectionDataSource.sections count] == 0)
  3518. return nil;
  3519. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3520. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3521. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3522. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3523. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3524. else titleSection = NSLocalizedString(titleSection,nil);
  3525. // Formato titolo
  3526. NSString *currentDevice = [CCUtility currentDevice];
  3527. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3528. visualEffectView = [[UIVisualEffectView alloc] init];
  3529. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3530. } else {
  3531. UIVisualEffect *blurEffect;
  3532. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3533. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3534. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3535. }
  3536. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3537. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3538. else shift = - 20;
  3539. } else shift = - 10;
  3540. // Title
  3541. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3542. titleLabel.backgroundColor = [UIColor clearColor];
  3543. titleLabel.textColor = [UIColor blackColor];
  3544. titleLabel.font = [UIFont systemFontOfSize:12];
  3545. titleLabel.textAlignment = NSTextAlignmentLeft;
  3546. titleLabel.text = titleSection;
  3547. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3548. [visualEffectView addSubview:titleLabel];
  3549. // Elements
  3550. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3551. elementLabel.backgroundColor = [UIColor clearColor];
  3552. elementLabel.textColor = [UIColor blackColor];;
  3553. elementLabel.font = [UIFont systemFontOfSize:12];
  3554. elementLabel.textAlignment = NSTextAlignmentRight;
  3555. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3556. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3557. NSUInteger rowsCount = [metadatas count];
  3558. if (rowsCount == 0) return nil;
  3559. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3560. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3561. [visualEffectView addSubview:elementLabel];
  3562. return visualEffectView;
  3563. }
  3564. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3565. {
  3566. return [_sectionDataSource.sections indexOfObject:title];
  3567. }
  3568. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3569. {
  3570. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3571. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3572. else
  3573. return nil;
  3574. }
  3575. /*
  3576. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3577. {
  3578. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3579. }
  3580. }
  3581. */
  3582. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3583. {
  3584. NSString *typeCell;
  3585. NSString *dataFile;
  3586. NSString *lunghezzaFile;
  3587. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3588. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3589. return [tableView dequeueReusableCellWithIdentifier:@"CellMainTransfer"];
  3590. }
  3591. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3592. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3593. else typeCell = @"CellMainTransfer";
  3594. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3595. // separator
  3596. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3597. // change color selection
  3598. UIView *selectionColor = [[UIView alloc] init];
  3599. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3600. cell.selectedBackgroundView = selectionColor;
  3601. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3602. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3603. // ----------------------------------------------------------------------------------------------------------
  3604. // DEFAULT
  3605. // ----------------------------------------------------------------------------------------------------------
  3606. cell.fileImageView.image = nil;
  3607. cell.statusImageView.image = nil;
  3608. cell.offlineImageView.image = nil;
  3609. cell.synchronizedImageView.image = nil;
  3610. cell.sharedImageView.image = nil;
  3611. cell.labelTitle.enabled = YES;
  3612. cell.labelTitle.text = @"";
  3613. cell.labelInfoFile.enabled = YES;
  3614. cell.labelInfoFile.text = @"";
  3615. cell.progressView.progress = 0.0;
  3616. cell.progressView.hidden = YES;
  3617. cell.cancelTaskButton.hidden = YES;
  3618. cell.reloadTaskButton.hidden = YES;
  3619. cell.stopTaskButton.hidden = YES;
  3620. // Encrypted color
  3621. if (metadata.cryptated) {
  3622. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3623. } else {
  3624. cell.labelTitle.textColor = [UIColor blackColor];
  3625. }
  3626. // ----------------------------------------------------------------------------------------------------------
  3627. // File Name & Folder
  3628. // ----------------------------------------------------------------------------------------------------------
  3629. // nome del file
  3630. cell.labelTitle.text = metadata.fileNamePrint;
  3631. // è una directory
  3632. if (metadata.directory) {
  3633. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3634. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3635. lunghezzaFile = @" ";
  3636. // ----------------------------------------------------------------------------------------------------------
  3637. // Favorite Folder
  3638. // ----------------------------------------------------------------------------------------------------------
  3639. if (metadata.favorite) {
  3640. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3641. }
  3642. } else {
  3643. // File
  3644. dataFile = [CCUtility dateDiff:metadata.date];
  3645. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3646. // Plist ancora da scaricare
  3647. if (metadata.cryptated && [metadata.title length] == 0) {
  3648. dataFile = @" ";
  3649. lunghezzaFile = @" ";
  3650. }
  3651. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithEtag:metadata.fileID activeAccount:app.activeAccount];
  3652. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3653. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3654. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3655. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3656. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3657. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3658. if (recordLocalFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3659. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3660. else
  3661. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3662. }
  3663. // Plist ancora da scaricare
  3664. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3665. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3666. cell.accessoryType = UITableViewCellAccessoryNone;
  3667. }
  3668. // ----------------------------------------------------------------------------------------------------------
  3669. // File Image View
  3670. // ----------------------------------------------------------------------------------------------------------
  3671. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3672. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3673. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3674. if (cell.fileImageView.image == nil) {
  3675. NSString *fileID = metadata.fileID;
  3676. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3677. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID]];
  3678. [app.icoImagesCache setObject:image forKey:fileID];
  3679. dispatch_async(dispatch_get_main_queue(), ^{
  3680. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3681. if (cell)
  3682. cell.fileImageView.image = image;
  3683. });
  3684. });
  3685. }
  3686. } else {
  3687. if (metadata.directory)
  3688. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3689. else
  3690. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3691. if (metadata.thumbnailExists)
  3692. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3693. }
  3694. // ----------------------------------------------------------------------------------------------------------
  3695. // Image Status cyptated & Lock Passcode
  3696. // ----------------------------------------------------------------------------------------------------------
  3697. // File Cyptated
  3698. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3699. cell.statusImageView.image = [UIImage imageNamed:@"lock"];
  3700. }
  3701. // Directory con passcode lock attivato
  3702. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3703. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPreficate:[NSPredicate predicateWithFormat:@"serverUrl = %@", dirServerUrl]];
  3704. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3705. cell.statusImageView.image = [UIImage imageNamed:@"passcode"];
  3706. // ----------------------------------------------------------------------------------------------------------
  3707. // Offline
  3708. // ----------------------------------------------------------------------------------------------------------
  3709. BOOL isOfflineFile = [CCCoreData isOfflineLocalEtag:metadata.fileID activeAccount:app.activeAccount];
  3710. if (isOfflineFile) {
  3711. cell.offlineImageView.image = [UIImage imageNamed:@"offline"];
  3712. }
  3713. // ----------------------------------------------------------------------------------------------------------
  3714. // Favorite
  3715. // ----------------------------------------------------------------------------------------------------------
  3716. if (metadata.favorite) {
  3717. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3718. }
  3719. // ----------------------------------------------------------------------------------------------------------
  3720. // Share
  3721. // ----------------------------------------------------------------------------------------------------------
  3722. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3723. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3724. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3725. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3726. // Aggiungiamo il Tap per le shared
  3727. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3728. if (isShare) {
  3729. if (metadata.directory) {
  3730. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3731. cell.sharedImageView.userInteractionEnabled = NO;
  3732. } else {
  3733. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3734. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3735. [tap setNumberOfTapsRequired:1];
  3736. cell.sharedImageView.userInteractionEnabled = YES;
  3737. [cell.sharedImageView addGestureRecognizer:tap];
  3738. }
  3739. }
  3740. if (isMounted) {
  3741. if (metadata.directory) {
  3742. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3743. cell.sharedImageView.userInteractionEnabled = NO;
  3744. } else {
  3745. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3746. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3747. [tap setNumberOfTapsRequired:1];
  3748. cell.sharedImageView.userInteractionEnabled = YES;
  3749. [cell.sharedImageView addGestureRecognizer:tap];
  3750. }
  3751. }
  3752. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3753. if (metadata.directory) {
  3754. if ([shareLink length] > 0)
  3755. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3756. if ([shareUserAndGroup length] > 0)
  3757. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3758. cell.sharedImageView.userInteractionEnabled = NO;
  3759. } else {
  3760. if ([shareLink length] > 0)
  3761. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3762. if ([shareUserAndGroup length] > 0)
  3763. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3764. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3765. [tap setNumberOfTapsRequired:1];
  3766. cell.sharedImageView.userInteractionEnabled = YES;
  3767. [cell.sharedImageView addGestureRecognizer:tap];
  3768. }
  3769. }
  3770. } else {
  3771. cell.sharedImageView.userInteractionEnabled = NO;
  3772. }
  3773. // ----------------------------------------------------------------------------------------------------------
  3774. // downloadFile
  3775. // ----------------------------------------------------------------------------------------------------------
  3776. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3777. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3778. else cell.statusImageView.image = [UIImage imageNamed:@"statusdownload"];
  3779. // sessionTaskIdentifier : RELOAD + STOP
  3780. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3781. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3782. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3783. cell.cancelTaskButton.hidden = NO;
  3784. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3785. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3786. cell.reloadTaskButton.hidden = NO;
  3787. }
  3788. // sessionTaskIdentifierPlist : RELOAD
  3789. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3790. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3791. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3792. cell.reloadTaskButton.hidden = NO;
  3793. }
  3794. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3795. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3796. if (progress > 0) {
  3797. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3798. else cell.progressView.progressTintColor = [UIColor blackColor];
  3799. cell.progressView.progress = progress;
  3800. cell.progressView.hidden = NO;
  3801. }
  3802. // ----------------------------------------------------------------------------------------------------------
  3803. // downloadFile Error
  3804. // ----------------------------------------------------------------------------------------------------------
  3805. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3806. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3807. if ([metadata.sessionError length] == 0)
  3808. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3809. else
  3810. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3811. }
  3812. }
  3813. // ----------------------------------------------------------------------------------------------------------
  3814. // uploadFile
  3815. // ----------------------------------------------------------------------------------------------------------
  3816. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3817. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3818. else cell.statusImageView.image = [UIImage imageNamed:@"statusupload"];
  3819. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3820. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3821. cell.cancelTaskButton.hidden = NO;
  3822. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3823. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3824. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3825. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusstopcrypto"];
  3826. else cell.statusImageView.image = [UIImage imageNamed:@"statusstop"];
  3827. cell.reloadTaskButton.hidden = NO;
  3828. cell.stopTaskButton.hidden = YES;
  3829. } else {
  3830. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3831. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3832. cell.stopTaskButton.hidden = NO;
  3833. cell.reloadTaskButton.hidden = YES;
  3834. }
  3835. // se non c'è una preview in bianconero metti l'immagine di default
  3836. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3837. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3838. cell.labelTitle.enabled = NO;
  3839. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3840. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3841. if (progress > 0) {
  3842. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3843. else cell.progressView.progressTintColor = [UIColor blackColor];
  3844. cell.progressView.progress = progress;
  3845. cell.progressView.hidden = NO;
  3846. }
  3847. // ----------------------------------------------------------------------------------------------------------
  3848. // uploadFileError
  3849. // ----------------------------------------------------------------------------------------------------------
  3850. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3851. cell.labelTitle.enabled = NO;
  3852. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3853. if ([metadata.sessionError length] == 0)
  3854. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3855. else
  3856. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3857. }
  3858. }
  3859. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3860. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3861. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3862. return cell;
  3863. }
  3864. - (void)setTableViewFooter
  3865. {
  3866. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3867. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3868. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3869. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3870. UIFont *appFont = [UIFont systemFontOfSize:12];
  3871. footerLabel.font = appFont;
  3872. footerLabel.textColor = [UIColor grayColor];
  3873. footerLabel.backgroundColor = [UIColor clearColor];
  3874. footerLabel.textAlignment = NSTextAlignmentCenter;
  3875. NSString *folders;
  3876. NSString *files;
  3877. NSString *footerText;
  3878. if (_sectionDataSource.directories > 1) {
  3879. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3880. } else if (_sectionDataSource.directories == 1){
  3881. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3882. } else {
  3883. folders = @"";
  3884. }
  3885. if (_sectionDataSource.files > 1) {
  3886. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3887. } else if (_sectionDataSource.files == 1){
  3888. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3889. } else {
  3890. files = @"";
  3891. }
  3892. if ([folders isEqualToString:@""]) {
  3893. footerText = files;
  3894. } else if ([files isEqualToString:@""]) {
  3895. footerText = folders;
  3896. } else {
  3897. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3898. }
  3899. footerLabel.text = footerText;
  3900. [footerView addSubview:footerLabel];
  3901. [self.tableView setTableFooterView:footerView];
  3902. }
  3903. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3904. {
  3905. NSString *textMessage;
  3906. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3907. // settiamo il record file.
  3908. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3909. // se non può essere selezionata deseleziona
  3910. if ([cell isEditing] == NO)
  3911. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3912. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3913. if (self.tableView.editing) {
  3914. [self setTitle];
  3915. return;
  3916. }
  3917. // test crash
  3918. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3919. if (indexPath.row >= [metadatas count]) return;
  3920. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3921. // se è in corso una sessione
  3922. if ([_metadata.session length] > 0) return;
  3923. if (_metadata.errorPasscode) {
  3924. // se UUID è nil lo sta ancora caricando quindi esci
  3925. if (!_metadata.uuid) return;
  3926. // esiste un hint ??
  3927. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3928. // qui !! la richiesta della nuova passcode
  3929. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3930. // stesso UUID ... la password è stata modificata !!!!!!
  3931. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3932. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3933. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3934. [alertView show];
  3935. } else {
  3936. // UUID diverso.
  3937. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3938. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3939. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3940. [alertView show];
  3941. }
  3942. // chiediamo la passcode e ricarichiamo tutto.
  3943. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3944. viewController.delegate = self;
  3945. viewController.fromType = CCBKPasscodeFromPasscode;
  3946. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3947. viewController.passcodeInputView.maximumLength = 64;
  3948. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3949. viewController.inputViewTitlePassword = NO;
  3950. viewController.title = [NCBrandOptions sharedInstance].brand;
  3951. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3952. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3953. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3954. [self presentViewController:navigationController animated:YES completion:nil];
  3955. }
  3956. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3957. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3958. NSString* selector;
  3959. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3960. else selector = selectorLoadPlist;
  3961. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3962. return;
  3963. }
  3964. // se il plist è caricato ed è un modello aprilo
  3965. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3966. // file
  3967. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3968. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3969. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3970. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3971. } else {
  3972. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3973. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3974. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3975. }
  3976. }
  3977. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3978. }
  3979. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3980. {
  3981. [self setTitle];
  3982. }
  3983. #pragma --------------------------------------------------------------------------------------------
  3984. #pragma mark ===== Synchronize Folder Cell =====
  3985. #pragma --------------------------------------------------------------------------------------------
  3986. - (void)synchronizeFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  3987. {
  3988. BOOL cryptated = NO;
  3989. CCCellMain *cell;
  3990. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  3991. tableMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3992. if (recordMetadata.directory == NO)
  3993. continue;
  3994. if ([[CCUtility stringAppendServerUrl:_serverUrl addFileName:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  3995. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  3996. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  3997. cryptated = recordMetadata.cryptated;
  3998. break;
  3999. }
  4000. }
  4001. if (!cell)
  4002. return;
  4003. if (animation) {
  4004. NSURL *myURL;
  4005. if (cryptated)
  4006. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  4007. else
  4008. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  4009. } else {
  4010. cell.synchronizedImageView.image = nil;
  4011. }
  4012. }
  4013. #pragma --------------------------------------------------------------------------------------------
  4014. #pragma mark ===== Navigation ====
  4015. #pragma --------------------------------------------------------------------------------------------
  4016. - (BOOL)shouldPerformSegue
  4017. {
  4018. // if background return
  4019. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4020. if (self.view.window == NO)
  4021. return NO;
  4022. // Collapsed ma siamo già in detail esci
  4023. if (self.splitViewController.isCollapsed)
  4024. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4025. // Video in esecuzione esci
  4026. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4027. return YES;
  4028. }
  4029. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4030. {
  4031. id viewController = segue.destinationViewController;
  4032. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4033. tableMetadata *metadata;
  4034. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4035. UINavigationController *nav = viewController;
  4036. _detailViewController = (CCDetail *)nav.topViewController;
  4037. } else {
  4038. _detailViewController = segue.destinationViewController;
  4039. }
  4040. if ([sender isKindOfClass:[tableMetadata class]]) {
  4041. metadata = sender;
  4042. [allRecordsDataSourceImagesVideos addObject:sender];
  4043. } else {
  4044. metadata = _metadata;
  4045. for (NSString *fileID in _sectionDataSource.allEtag) {
  4046. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4047. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4048. [allRecordsDataSourceImagesVideos addObject:metadata];
  4049. }
  4050. }
  4051. _detailViewController.metadataDetail = metadata;
  4052. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4053. _detailViewController.dateFilterQuery = nil;
  4054. _detailViewController.isCameraUpload = NO;
  4055. [_detailViewController setTitle:metadata.fileNamePrint];
  4056. }
  4057. // can i go to next viewcontroller
  4058. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4059. {
  4060. NSString *nomeDir;
  4061. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4062. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  4063. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4064. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPreficate:[NSPredicate predicateWithFormat:@"serverUrl = %@", dirServerUrl]];
  4065. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4066. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4067. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4068. viewController.delegate = self;
  4069. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4070. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4071. viewController.inputViewTitlePassword = YES;
  4072. if ([CCUtility getSimplyBlockCode]) {
  4073. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4074. viewController.passcodeInputView.maximumLength = 6;
  4075. } else {
  4076. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4077. viewController.passcodeInputView.maximumLength = 64;
  4078. }
  4079. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4080. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4081. viewController.touchIDManager = touchIDManager;
  4082. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4083. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4084. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4085. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4086. [self presentViewController:navController animated:YES completion:nil];
  4087. return;
  4088. }
  4089. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4090. else nomeDir = _metadata.fileName;
  4091. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4092. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4093. if (viewController.isViewLoaded == false || viewController == nil) {
  4094. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4095. viewController.isFolderEncrypted = _metadata.cryptated;
  4096. viewController.serverUrl = serverUrlPush;
  4097. viewController.titleMain = _metadata.fileNamePrint;
  4098. viewController.textBackButton = _titleMain;
  4099. // save self
  4100. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4101. }
  4102. // OFF SearchBar
  4103. [viewController cancelSearchBar];
  4104. [self.navigationController pushViewController:viewController animated:YES];
  4105. }
  4106. }
  4107. @end