CCMain.m 250 KB

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