CCMain.m 246 KB

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